/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.suli.outHouse.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.entity.Result;
import me.zhengjie.modules.mnt.websocket.MsgType;
import me.zhengjie.modules.mnt.websocket.SocketMsg;
import me.zhengjie.modules.mnt.websocket.WebSocketServer;
import me.zhengjie.suli.document.domain.Tray;
import me.zhengjie.suli.document.repository.TrayRepository;
import me.zhengjie.suli.inventory.domain.Inventory;
import me.zhengjie.suli.inventory.repository.InventoryRepository;
import me.zhengjie.suli.location.domain.Location;
import me.zhengjie.suli.location.repository.LocationRepository;
import me.zhengjie.suli.outHouse.domain.OrderDetail;
import me.zhengjie.suli.outHouse.domain.Orders;
import me.zhengjie.suli.outHouse.repository.OrderDetailRepository;
import me.zhengjie.suli.outHouse.repository.OrdersRepository;
import me.zhengjie.suli.outHouse.service.OrdersService;
import me.zhengjie.suli.outHouse.service.dto.OrdersDto;
import me.zhengjie.suli.outHouse.service.dto.OrdersQueryCriteria;
import me.zhengjie.suli.outHouse.service.mapstruct.OrdersMapper;
import me.zhengjie.suli.roll.domain.Roll;
import me.zhengjie.suli.roll.repository.RollRepository;
import me.zhengjie.suli.rollDetail.domain.RollDetail;
import me.zhengjie.suli.rollDetail.repository.RollDetailRepository;
import me.zhengjie.suli.tasks.domain.TaskDetail;
import me.zhengjie.suli.tasks.domain.Tasks;
import me.zhengjie.suli.tasks.repository.TaskDetailRepository;
import me.zhengjie.suli.tasks.repository.TasksRepository;
import me.zhengjie.suli.toHouse.domain.Receipt;
import me.zhengjie.suli.toHouse.domain.ReceiptDetail;
import me.zhengjie.suli.toHouse.repository.ReceiptDetailRepository;
import me.zhengjie.suli.toHouse.repository.ReceiptRepository;
import me.zhengjie.suli.toHouse.service.ReceiptService;
import me.zhengjie.suli.wcs.domain.AgvTaskDetail;
import me.zhengjie.suli.wcs.domain.AgvTasks;
import me.zhengjie.suli.wcs.repository.AgvTaskDetailRepository;
import me.zhengjie.suli.wcs.repository.AgvTasksRepository;
import me.zhengjie.suli.wcs.service.AgvTasksService;
import me.zhengjie.suli.wcs.service.dto.AgvSendTask;
import me.zhengjie.suli.wcs.service.dto.AgvSendTaskDescribe;
import me.zhengjie.suli.wcs.service.dto.AgvSendTasks;
import me.zhengjie.util.CommonUtil;
import me.zhengjie.util.UuidUtil;
import me.zhengjie.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.acl.Group;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WYH
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-02-01
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class OrdersServiceImpl implements OrdersService {

    private final OrdersRepository ordersRepository;
    private final OrdersMapper ordersMapper;
    private final CommonUtil commonUtil;
    private final OrderDetailRepository orderDetailRepository;
    private final InventoryRepository inventoryRepository;
    private final AgvTasksRepository agvTasksRepository;
    private final AgvTaskDetailRepository agvTaskDetailRepository;
    private final TasksRepository tasksRepository;
    private final TaskDetailRepository taskDetailRepository;
    private final AgvTasksService agvTasksService;
    private final LocationRepository locationRepository;
    private final TrayRepository trayRepository;
    private final ReceiptService receiptService;
    private final ReceiptDetailRepository receiptDetailRepository;
    private final ReceiptRepository receiptRepository;
    private final RollRepository rollRepository;
    private final RollDetailRepository rollDetailRepository;
    private final JdbcTemplate jdbcTemplate;
    @Value("${agv.port}")
    private String agvPort;

    @Value("${agv.ip}")
    private String agvIp;


    @Override
    public Map<String, Object> queryAll(OrdersQueryCriteria criteria, Pageable pageable) {
        Page<Orders> page = ordersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        log.info(PageUtil.toPage(page.map(ordersMapper::toDto)).toString());
        return PageUtil.toPage(page.map(ordersMapper::toDto));
    }

    @Override
    public List<OrdersDto> queryAll(OrdersQueryCriteria criteria) {
        return ordersMapper.toDto(ordersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public OrdersDto findById(String id) {
        Orders orders = ordersRepository.findById(id).orElseGet(Orders::new);
        ValidationUtil.isNull(orders.getId(), "Orders", "id", id);
        return ordersMapper.toDto(orders);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrdersDto create(Orders resources) {
        return ordersMapper.toDto(ordersRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Orders resources) {
        Orders orders = ordersRepository.findById(resources.getId()).orElseGet(Orders::new);
        ValidationUtil.isNull(orders.getId(), "Orders", "id", resources.getId());
        orders.copy(resources);
        ordersRepository.save(orders);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            ordersRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<String> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderDetailRepository.findByMainIds(all);
        List<Orders> allById = ordersRepository.findAllById(all);
        for (OrderDetail orderDetail : orderDetailList) {
            List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceId(orderDetail.getOrderDetailCode());
            Orders ordersDto = allById.stream().filter(item -> item.getId().equals(orderDetail.getMainId())).findFirst().orElse(null);
            for (TaskDetail taskDetail : taskDetailList) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("出库单号", ordersDto.getSourceDocument());
                map.put("物料名称", orderDetail.getMaterialName());
                map.put("物料编码", orderDetail.getMaterialCode());
                map.put("箱号", taskDetail.getPkList());
                map.put("批次", taskDetail.getLotNo());
                map.put("供应商", taskDetail.getSuNo());
                map.put("出货数量", taskDetail.getPkQty().intValue());
                map.put("创建时间", orderDetail.getCreateTime().toString());
                map.put("更新时间", orderDetail.getUpdateTime().toString());
                list.add(map);
            }
        }
        FileUtil.downloadExcel(list, response);
    }


    @Override
    public String byCarDocument(String param) {
        if (null == param || "".equalsIgnoreCase(param)) {
            return null;
        }
        log.info("接收到出库任务" + param);
        List<JSONObject> jsonObject = JSON.parseArray(param, JSONObject.class);
        List<OrderDetail> orderDetails = new ArrayList<>();
        Orders orders = new Orders();
        Snowflake snowflake = new Snowflake();
        String uuid = snowflake.nextIdStr();//头表id
        orders.setId(uuid);
        orders.setIsSendSccs(0);
        orders.setOrderCode(UuidUtil.genCode());
        orders.setOrderType(1);
        orders.setOrderStatus(0);
        orders.setActQty(new BigDecimal(0));
        orders.setCreateTime(new Timestamp(new Date().getTime()));
        BigDecimal planQty = new BigDecimal(0);

        for (JSONObject object : jsonObject) {
            if (null == object.getString("el_no") || object.getString("el_no").equals("")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的物料编号为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的物料编号为空");
            }
            if (null == object.getString("el_name") || object.getString("el_name").equals("")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的物料名称为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的物料名称为空");
            }

            if (null == object.getBigDecimal("pd_mrqty")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的计划数量为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的计划数量为空");
            }
            if(object.getString("el_name").equals("压缩机完成品")){
                orders.setPlanQty(object.getBigDecimal("pd_mrqty"));
                continue;
            }
            List<Inventory> inventories = inventoryRepository.findByMaterialCode(object.getString("el_no"));
            if (null == inventories || inventories.size() == 0) {
                orders.setOrderStatus(3);
            }
            if (null != object.getString("el_invid") && object.getString("el_invid").equals("P")) {
                orders.setPlanQty(object.getBigDecimal("pd_mrqty"));
                continue;
            }
            boolean flag = false;
            for (OrderDetail orderDetail : orderDetails) {
                if (orderDetail.getMaterialCode().equals(object.getString("el_no"))) {
                    orderDetail.setPlanQty(orderDetail.getPlanQty().add(object.getBigDecimal("mr_qty")));
                    flag = true;
                }
            }
            if (flag) {
                continue;
            }
            orders.setSourceDocument(object.getString("pd_list"));//随车单号
            orders.setCustom(object.getString("cu_name"));
            OrderDetail order = new OrderDetail();
            order.setId(snowflake.nextIdStr());
            order.setOrderDetailCode(UuidUtil.genCode());
            order.setMainId(uuid);
            order.setActQty(new BigDecimal(0));
            order.setMaterialCode(null != object.getString("el_no") ? object.getString("el_no") : null);//物料编码
            order.setMaterialName(null != object.getString("el_name") ? object.getString("el_name") : null);//物料名称
            order.setPlanQty(null != object.getBigDecimal("pd_mrqty") ? object.getBigDecimal("pd_mrqty") : null); //计划数量
            order.setStatus(1);
            order.setSuNo(object.getString("su_no"));
            order.setLocationCode(null != object.getString("mt_area") ? object.getString("mt_area") : null);//发出库位
            order.setWarehouseCode(object.getString("mt_area"));
            order.setUnitCode(null != object.getString("el_unit") ? object.getString("el_unit") : null);//单位
            order.setCreateBy(null != object.getString("rtd_user") ? object.getString("rtd_user") : null);//操作人员
            order.setCreateTime(new Timestamp(new Date().getTime()));
            planQty = planQty.add(order.getPlanQty());
            orderDetails.add(order);
        }
        if (null == orders.getPlanQty() || orders.getPlanQty().compareTo(BigDecimal.ZERO) == 0){
            orders.setPlanQty(planQty);
        }
        ordersRepository.save(orders);
        orderDetailRepository.saveAll(orderDetails);

        return orders.getId();
    }

    @Override
    public String rollByCar(String param) {
        if (null == param || "".equalsIgnoreCase(param)) {
            return "参数为空，请检查";
        }
        log.info("接收到出库任务" + param);
        List<JSONObject> jsonObject = JSON.parseArray(param, JSONObject.class);
        List<OrderDetail> orderDetails = new ArrayList<>();
        Orders orders = new Orders();
        Snowflake snowflake = new Snowflake();
        String uuid = snowflake.nextIdStr();//头表id
        orders.setId(uuid);
        orders.setIsSendSccs(0);
        orders.setOrderCode(UuidUtil.genCode());
        orders.setOrderType(2);
        orders.setActQty(new BigDecimal(0));
        orders.setOrderStatus(0);
        orders.setCreateTime(new Timestamp(new Date().getTime()));
        BigDecimal planQty = new BigDecimal(0);
        for (JSONObject object : jsonObject) {
            if (null == object.getString("el_no") || object.getString("el_no").equals("")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的物料编号为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的物料编号为空");
            }
            if (null == object.getString("el_name") || object.getString("el_name").equals("")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的物料名称为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的物料名称为空");
            }
            if (null == object.getBigDecimal("pd_mrqty")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的计划数量为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的计划数量为空");
            }
            if (object.getString("el_name").equals("压缩机完成品")){
                orders.setPlanQty(object.getBigDecimal("pd_mrqty"));
                continue;
            }
            List<Inventory> inventories = inventoryRepository.findByMaterialCode(object.getString("el_no"));
            if (null == inventories || inventories.size() == 0) {
                orders.setOrderStatus(3);
            }
            if (null != object.getString("el_invid") && object.getString("el_invid").equals("P")) {
                orders.setPlanQty(object.getBigDecimal("pd_mrqty"));
                continue;
            }
            boolean flag = false;
            for (OrderDetail orderDetail : orderDetails) {
                if (orderDetail.getMaterialCode().equals(object.getString("el_no"))) {
                    orderDetail.setPlanQty(orderDetail.getPlanQty().add(object.getBigDecimal("mr_qty")));
                    flag = true;
                }
            }
            if (flag) {
                continue;
            }
            orders.setSourceDocument(object.getString("pd_list"));//随车单号
            OrderDetail order = new OrderDetail();
            order.setId(snowflake.nextIdStr());
            order.setActQty(new BigDecimal(0));
            order.setOrderDetailCode(UuidUtil.genCode());
            order.setMainId(uuid);
            order.setSuNo(object.getString("su_no"));
            order.setMaterialCode(null != object.getString("el_no") ? object.getString("el_no") : null);//物料编码
            order.setMaterialName(null != object.getString("el_name") ? object.getString("el_name") : null);//物料名称
            order.setPlanQty(null != object.getBigDecimal("pd_mrqty") ? object.getBigDecimal("pd_mrqty") : null); //计划数量
            order.setStatus(1);
            order.setLocationCode(null != object.getString("mt_area") ? object.getString("mt_area") : null);//发出库位
            order.setUnitCode(null != object.getString("el_unit") ? object.getString("el_unit") : null);//单位
            order.setCreateBy(null != object.getString("rtd_user") ? object.getString("rtd_user") : null);//操作人员
            order.setCreateTime(new Timestamp(new Date().getTime()));
            order.setWarehouseCode(object.getString("mt_area"));
            planQty = planQty.add(order.getPlanQty());
            orderDetails.add(order);
        }
        if (null == orders.getPlanQty() || orders.getPlanQty().compareTo(BigDecimal.ZERO) == 0){
            orders.setPlanQty(planQty);
        }
        ordersRepository.save(orders);
        orderDetailRepository.saveAll(orderDetails);

        return orders.getId();
    }

    @Override
    public String costCenterUse(String param) {
        if (null == param || "".equalsIgnoreCase(param)) {
            return "参数为空，请检查";
        }
        log.info("接收到出库任务" + param);
        List<JSONObject> jsonObject = JSON.parseArray(param, JSONObject.class);
        List<OrderDetail> orderDetails = new ArrayList<>();
        Orders orders = new Orders();
        Snowflake snowflake = new Snowflake();
        String uuid = snowflake.nextIdStr();//头表id
        orders.setId(uuid);
        orders.setIsSendSccs(0);
        orders.setActQty(new BigDecimal(0));
        orders.setOrderCode(UuidUtil.genCode());
        orders.setOrderType(4);
        orders.setOrderStatus(0);
        orders.setCreateTime(new Timestamp(new Date().getTime()));
        BigDecimal planQty = new BigDecimal(0);
        for (JSONObject object : jsonObject) {
            if (null == object.getString("el_no") || object.getString("el_no").equals("")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的物料编号为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的物料编号为空");
            }
            if (null == object.getString("el_name") || object.getString("el_name").equals("")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的物料名称为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的物料名称为空");
            }
            if (null == object.getBigDecimal("mr_qty")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的计划数量为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的计划数量为空");
            }
            List<Inventory> inventories = inventoryRepository.findByMaterialCode(object.getString("el_no"));
            if (null == inventories || inventories.size() == 0) {
                orders.setOrderStatus(3);
            }
            if (null != object.getString("el_invid") && object.getString("el_invid").equals("P")) {
                orders.setPlanQty(object.getBigDecimal("pd_mrqty"));
                continue;
            }
            boolean flag = false;
            for (OrderDetail orderDetail : orderDetails) {
                if (orderDetail.getMaterialCode().equals(object.getString("el_no"))) {
                    orderDetail.setPlanQty(orderDetail.getPlanQty().add(object.getBigDecimal("mr_qty")));
                    flag = true;
                }
            }
            if (flag) {
                continue;
            }
            orders.setSourceDocument(object.getString("mr_list"));//随车单号
            OrderDetail order = new OrderDetail();
            order.setId(snowflake.nextIdStr());
            order.setOrderDetailCode(UuidUtil.genCode());
            order.setMainId(uuid);
            order.setActQty(new BigDecimal(0));
            order.setSuNo(null != object.getString("su_no") ? object.getString("su_no") : null);
            order.setMaterialCode(null != object.getString("el_no") ? object.getString("el_no") : null);//物料编码
            order.setMaterialName(null != object.getString("el_name") ? object.getString("el_name") : null);//物料名称
            order.setPlanQty(null != object.getBigDecimal("mr_qty") ? object.getBigDecimal("mr_qty") : null); //计划数量
            order.setStatus(1);
            order.setSuNo(object.getString("su_no"));
            order.setLocationCode(null != object.getString("mt_area") ? object.getString("mt_area") : null);//发出库位
            order.setWarehouseCode(null != object.getString("mt_area") ? object.getString("mt_area") : null);//发出库位
            order.setUnitCode(null != object.getString("el_unit") ? object.getString("el_unit") : null);//单位
            order.setCreateBy(null != object.getString("rtd_user") ? object.getString("rtd_user") : null);//操作人员
            order.setCreateTime(new Timestamp(new Date().getTime()));
            orderDetails.add(order);
        }
        if (null == orders.getPlanQty()) {
            orders.setPlanQty(new BigDecimal(0));
            for (OrderDetail orderDetail : orderDetails) {
                orders.setPlanQty(orders.getPlanQty().add(orderDetail.getPlanQty()));
            }
        }
        ordersRepository.save(orders);
        orderDetailRepository.saveAll(orderDetails);
        return orders.getId();
    }


    @Override
    public String receiveSalesInstructions(String param) {
        if (null == param || "".equalsIgnoreCase(param)) {
            return "参数为空，请检查";
        }
        log.info("接收到出库任务" + param);
        List<JSONObject> jsonObject = JSON.parseArray(param, JSONObject.class);
        List<OrderDetail> orderDetails = new ArrayList<>();
        Orders orders = new Orders();
        Snowflake snowflake = new Snowflake();
        String uuid = snowflake.nextIdStr();//头表id
        orders.setId(uuid);
        orders.setIsSendSccs(0);
        orders.setActQty(new BigDecimal(0));
        orders.setOrderCode(UuidUtil.genCode());
        orders.setOrderType(3);
        orders.setOrderStatus(0);
        orders.setCreateTime(new Timestamp(new Date().getTime()));
        BigDecimal planQty = new BigDecimal(0);
        for (JSONObject object : jsonObject) {
            if (null == object.getString("el_no") || object.getString("el_no").equals("")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的物料编号为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的物料编号为空");
            }
            if (null == object.getString("el_name") || object.getString("el_name").equals("")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的物料名称为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的物料名称为空");
            }
            if (null == object.getBigDecimal("pd_mrqty")) {
                log.info("出库单号为：" + object.getString("pd_list") + "的计划数量为空");
                throw new RuntimeException("出库单号为：" + object.getString("pd_list") + "的计划数量为空");
            }
            List<Inventory> inventories = inventoryRepository.findByMaterialCode(object.getString("el_no"));
            if (null == inventories || inventories.size() == 0) {
                orders.setOrderStatus(4);
            }
            if (object.getString("el_invid").equals("P")) {
                orders.setPlanQty(object.getBigDecimal("pd_mrqty"));
                continue;
            }
            orders.setSourceDocument(object.getString("pd_list"));//随车单号
            OrderDetail order = new OrderDetail();
            order.setId(snowflake.nextIdStr());
            order.setActQty(new BigDecimal(0));
            order.setOrderDetailCode(UuidUtil.genCode());
            order.setMainId(uuid);
            order.setMaterialCode(null != object.getString("el_no") ? object.getString("el_no") : null);//物料编码
            order.setMaterialName(null != object.getString("el_name") ? object.getString("el_name") : null);//物料名称
            order.setPlanQty(null != object.getBigDecimal("pd_mrqty") ? object.getBigDecimal("pd_mrqty") : null); //计划数量
            order.setStatus(1);
            order.setSuNo(object.getString("su_no"));
//            order.setLocationCode(null != object.getString("mt_area")?object.getString("mt_area"):null);//发出库位
//            order.setUnitCode(null != object.getString("el_unit")?object.getString("el_unit"):null);//单位
//            order.setCreateBy(null != object.getString("rtd_user")?object.getString("rtd_user"):null);//操作人员
            order.setCreateTime(new Timestamp(new Date().getTime()));
            orderDetails.add(order);
        }
        ordersRepository.save(orders);
        orderDetailRepository.saveAll(orderDetails);
        return orders.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addOutBoundTask(String id) {
        int q = 0;
        Orders allById = ordersRepository.findById(id).orElse(null);
        if (allById.getOrderStatus() != 3 && allById.getOrderStatus() != 0) {
            return new Result(102, "单据存在异常", null);
        }
        Snowflake snowflake = new Snowflake();
        log.info("接收到出库订单：" + allById.getOrderCode());
        List<OrderDetail> byMainId = orderDetailRepository.findByMainId(allById.getId());
        Map<String, Object> map = new HashMap<>();//返回的数据 格式 {物料名称：{箱号：数量}}
        List<Inventory> inventoriesList = new ArrayList<>();//选中的库存
        List<TaskDetail> taskDetailList = new ArrayList<>();//wms任务详细
        List<Tasks> wmsTasksList = new ArrayList<>();//wms任务
        List<OrderDetail> orderDetails = new ArrayList<>();//订单详细列表
        List<String> collect = byMainId.stream().map(OrderDetail::getMaterialCode).distinct().collect(Collectors.toList());
        List<Inventory> byMaterialCodes = inventoryRepository.findByMaterialCodesAndIsHold(collect);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        for (OrderDetail orderDetail : byMainId) {
            List<Inventory> in = new ArrayList<>();
            in = byMaterialCodes.stream().filter(item -> item.getMaterialCode().equals(orderDetail.getMaterialCode())).collect(Collectors.toList());
            if (null != orderDetail.getSuNo() && !orderDetail.getSuNo().equals("")) {
                if (allById.getOrderType() == 6) {
                    in = in.stream().filter(item -> null != item.getSuNo() && item.getSuNo().equals(orderDetail.getSuNo())).collect(Collectors.toList());
                } else {
                    in = in.stream().filter(item -> null != item.getSuName() && item.getSuName().equals(orderDetail.getSuNo())).collect(Collectors.toList());
                    if (null == in || in.size() == 0){
                        in = in.stream().filter(item -> null != item.getSuNo() && item.getSuNo().equals(orderDetail.getSuNo())).collect(Collectors.toList());
                    }
                }
            }
            if (allById.getOrderType() != 1 && allById.getOrderType() != 2 && null != orderDetail.getWarehouseCode() && !"".equals(orderDetail.getWarehouseCode())){
                in = in.stream().filter(item -> null != item && null != item.getZoneCode() && item.getZoneCode().equals(orderDetail.getWarehouseCode())).collect(Collectors.toList());
            }
            if (allById.getOrderType() == 5) {
                in = in.stream().filter(item -> item.getVmiCode() == null || item.getVmiCode().equals("") || item.getVmiCode().equals("N")).collect(Collectors.toList());
            } else if (allById.getOrderType() == 6) {
                in = in.stream().filter(item -> null != item.getVmiCode() && item.getVmiCode().equals("Y")).collect(Collectors.toList());
            }
            if (null == in || in.size() == 0) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("el_no", orderDetail.getMaterialCode());
                jsonObject1.put("el_name", orderDetail.getMaterialName());
                jsonObject1.put("count", orderDetail.getPlanQty().intValue());
                jsonObject1.put("inventoryCount", 0);
                jsonObject1.put("inventoryNotCount", orderDetail.getPlanQty().intValue());
                jsonObject1.put("su_no", orderDetail.getSuNo());
                jsonObjectList.add(jsonObject1);
            } else {
                List<BigDecimal> collect2 = in.stream().map(Inventory::getAvailableQuantity).collect(Collectors.toList());
                BigDecimal reduce = collect2.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                if (null != orderDetail.getPlanQty() && null != reduce && orderDetail.getPlanQty().compareTo(reduce) > 0) {
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("el_no", orderDetail.getMaterialCode());
                    jsonObject1.put("el_name", orderDetail.getMaterialName());
                    jsonObject1.put("count", orderDetail.getPlanQty().intValue());
                    jsonObject1.put("inventoryCount", reduce.intValue());
                    jsonObject1.put("inventoryNotCount", orderDetail.getPlanQty().intValue() - reduce.intValue());
                    jsonObject1.put("su_no", orderDetail.getSuNo());
                    jsonObjectList.add(jsonObject1);
                }
            }

        }
        if (null != jsonObjectList && jsonObjectList.size() != 0) {
            ordersRepository.delete(allById);
            orderDetailRepository.deleteAll(byMainId);
            return new Result(102, "数量不足", jsonObjectList);
        }
        for (OrderDetail ordersDetail : byMainId) {
            List<Inventory> inventories = new ArrayList<>();
            /**查询总数看够不够出 */
            List<Inventory> inventoryList = new ArrayList<>();
            List<Inventory> inventoryByMaterialCodes = new ArrayList<>();
//            if (null != ordersDetail.getWarehouseCode() && !ordersDetail.getWarehouseCode().equals("")){
//                inventoryList = byMaterialCodes.stream().filter(item -> null != item.getZoneCode() && item.getZoneCode().equals(ordersDetail.getWarehouseCode())).collect(Collectors.toList());
//            }else{
            inventoryList = byMaterialCodes;
//            }
            if (null == inventoryList || inventoryList.size() == 0) {
                inventoryList = byMaterialCodes;
            }
            /** 如果有选择供应商就按照供应商出库 */
            if (null != ordersDetail.getSuNo() && !ordersDetail.getSuNo().equals("")) {
                if (allById.getOrderType() == 6) {
                    inventoryByMaterialCodes = inventoryList.stream().filter(inventory -> null != inventory.getSuNo() && inventory.getMaterialCode().equals(ordersDetail.getMaterialCode()) && inventory.getSuNo().equals(ordersDetail.getSuNo())).collect(Collectors.toList());
                } else {
                    inventoryByMaterialCodes = inventoryList.stream().filter(inventory -> null != inventory.getSuName() && inventory.getMaterialCode().equals(ordersDetail.getMaterialCode()) && inventory.getSuName().equals(ordersDetail.getSuNo())).collect(Collectors.toList());
                    if (null == inventoryByMaterialCodes || inventoryByMaterialCodes.size() == 0){
                        inventoryByMaterialCodes = inventoryList.stream().filter(inventory -> null != inventory.getSuNo() && inventory.getMaterialCode().equals(ordersDetail.getMaterialCode()) && inventory.getSuNo().equals(ordersDetail.getSuNo())).collect(Collectors.toList());
                    }
                }
            } else {
                inventoryByMaterialCodes = inventoryList.stream().filter(inventory -> inventory.getMaterialCode().equals(ordersDetail.getMaterialCode())).collect(Collectors.toList());
            }
            inventoryByMaterialCodes = inventoryByMaterialCodes.stream().filter(item -> item.getAvailableQuantity().compareTo(new BigDecimal(0)) > 0).collect(Collectors.toList());
            //如果是411或者311就按照仓库再次筛选
            if (allById.getOrderType() != 1 && allById.getOrderType() != 2 && null != ordersDetail.getWarehouseCode() && !ordersDetail.getWarehouseCode().equals("")){
                inventoryByMaterialCodes = inventoryByMaterialCodes.stream().filter(inventory -> inventory.getZoneCode().equals(ordersDetail.getWarehouseCode())).collect(Collectors.toList());
            }
            if (allById.getOrderType() == 5) {
                inventoryByMaterialCodes = inventoryByMaterialCodes.stream().filter(item -> item.getVmiCode() == null || item.getVmiCode().equals("") || item.getVmiCode().equals("N")).collect(Collectors.toList());
            } else if (allById.getOrderType() == 6) {
                inventoryByMaterialCodes = inventoryByMaterialCodes.stream().filter(item -> null != item.getVmiCode() && item.getVmiCode().equals("Y")).collect(Collectors.toList());
            }
            /** 根据物料编号查询未冻结的库存,按暂存区排序*/
            inventoryByMaterialCodes = inventoryByMaterialCodes.stream().sorted(Comparator.comparing(item -> null == item.getElMkDate())).collect(Collectors.toList());
            List<Inventory> collect1 = inventoryByMaterialCodes.stream().filter(item -> null == item.getElMkDate() || item.getElMkDate().equals("")).collect(Collectors.toList());
            List<Inventory> collect2 = inventoryByMaterialCodes.stream().filter(item -> null != item.getElMkDate() && !item.getElMkDate().equals("")).collect(Collectors.toList());
            List<Inventory> inventories1 = collect2.stream().sorted(Comparator.comparing(item -> Integer.valueOf(item.getElMkDate().replaceAll("/", "")))).collect(Collectors.toList());
            inventories1.addAll(collect1);
            inventories1 = inventories1.stream().sorted(Comparator.comparing(item -> !item.getWarehouseLocation().equals("暂存区"))).collect(Collectors.toList());
            List<Inventory> byLocationCode = new ArrayList<>();
            byLocationCode.addAll(inventories1.stream().filter(item -> null == item.getVmiCode() || "".equals(item.getVmiCode()) || item.getVmiCode().equals("N")).collect(Collectors.toList()));
            byLocationCode.addAll(inventories1.stream().filter(item -> null != item.getVmiCode() && item.getVmiCode().equals("Y")).collect(Collectors.toList()));
            Map<String, List<Inventory>> listMap = byLocationCode.stream().collect(Collectors.groupingBy(Inventory::getElMkDate));
            List<Inventory> list1 = new ArrayList<>();
            List<Map.Entry<String, List<Inventory>>> listMapOne = listMap.entrySet().stream().sorted(Comparator.comparing(item -> Integer.valueOf(item.getKey().replaceAll("/", "")))).collect(Collectors.toList());
            for (Map.Entry<String, List<Inventory>> stringListEntry : listMapOne) {
                List<Inventory> collect3 = stringListEntry.getValue().stream().filter(item -> null != item.getWarehouseLocation() && item.getWarehouseLocation().equals("暂存区")).sorted(Comparator.comparing(Inventory::getStartDate)).collect(Collectors.toList());
                List<Inventory> listMapTwo = new ArrayList<>();
                listMapTwo.addAll(collect3);
                List<Inventory> listMapThree = stringListEntry.getValue().stream().filter(item -> null != item.getWarehouseLocation() && !item.getWarehouseLocation().equals("暂存区")).sorted(Comparator.comparing(Inventory::getStartDate)).collect(Collectors.toList());
                listMapTwo.addAll(listMapThree);
                list1.addAll(listMapTwo);
            }
            List<Inventory> list = new ArrayList<>();
            if (allById.getOrderType() == 1 || allById.getOrderType() == 2){
                List<Inventory> vmi = list1.stream().filter(item -> null != item.getVmiCode() && item.getVmiCode().equals("Y")).collect(Collectors.toList());
                List<Inventory> noVmi = list1.stream().filter(item -> null == item.getVmiCode() || item.getVmiCode().equals("") || item.getVmiCode().equals("N")).collect(Collectors.toList());
                list.addAll(noVmi);//非vmi的
                list.addAll(vmi);//vmi的
            }else{
                list.addAll(list1);
            }
            if (null != list && !list.isEmpty()) {
                BigDecimal material = ordersDetail.getPlanQty();
                /** 查询出来的物料循环计算几箱够出库 */
                for (Inventory inventory : list) {
                    Inventory inventory1 = inventories.stream().filter(item -> item.getId().equals(inventory.getId())).findFirst().orElse(null);
                    if (null != inventory1){
                        continue;
                    }
                    if (material.compareTo(new BigDecimal(0)) <= 0) {
                        break;
                    }
                    if (inventory.getAvailableQuantity().compareTo(new BigDecimal(0)) <= 0) {
                        continue;
                    }
                    /** 当前库存物料不够的情况下 */
                    if (material.compareTo(inventory.getAvailableQuantity()) > 0) {
                        material = material.subtract(inventory.getAvailableQuantity());
                        inventory.setHoldQuantity(inventory.getAvailableQuantity());
                        inventory.setAvailableQuantity(new BigDecimal(0));
                        inventories.add(inventory);
                        /** 当前库存物料正好的情况下 */
                    } else if (material.compareTo(inventory.getAvailableQuantity()) == 0) {
                        inventory.setHoldQuantity(inventory.getAvailableQuantity());
                        inventory.setAvailableQuantity(new BigDecimal(0));
                        inventories.add(inventory);
                        material = material.subtract(inventory.getAvailableQuantity());
                        break;
                        /** 当前库存物料多的情况下 */
                    } else {
                        inventory.setHoldQuantity(material);
                        BigDecimal count = material;
                        material = material.subtract(inventory.getAvailableQuantity());
                        inventory.setAvailableQuantity(inventory.getAvailableQuantity().subtract(count));
                        inventory.setHoldQuantity(count);
                        if (inventory.getIsHold() == 1) {
                            inventory.setTotal(material);
                        }
                        inventories.add(inventory);
                    }
                }
                for (Inventory inventory : inventories) {
                    Tasks wmsTask = new Tasks();
                    wmsTask.setId(UuidUtil.genCode());
                    wmsTask.setTaskType(2);
                    wmsTask.setSourceCode(allById.getSourceDocument());
                    wmsTask.setStartTime(new Timestamp(new Date().getTime()));
                    wmsTask.setTrayCode(inventory.getTrayCode());
                    wmsTask.setTaskCode(ordersDetail.getOrderDetailCode());
                    wmsTask.setElUnit(inventory.getElUnit());
                    wmsTask.setElName(inventory.getMaterialName());
                    wmsTask.setElNo(inventory.getMaterialCode());
                    wmsTask.setLocationFrom(inventory.getWarehouseLocation());
                    wmsTask.setLocationTo("CY02");
                    wmsTask.setStatus(1);
                    wmsTasksList.add(wmsTask);
                    TaskDetail taskDetail = new TaskDetail();
                    if (null != inventory.getWarehouseLocation())
                        if (inventory.getWarehouseLocation().equals("暂存区")) {
                            /** 暂存区不发Agv任务，增加WMS任务详细 */
                            ordersDetail.setStatus(2);
                            taskDetail.setId(UuidUtil.genCode());
                            taskDetail.setTaskId(wmsTask.getId());
                            taskDetail.setStatus(1);
                            taskDetail.setEl_no(inventory.getMaterialCode());
                            taskDetail.setEl_unit(inventory.getElUnit());
                            taskDetail.setIsZanCun(1);
                            taskDetail.setZoneCode(inventory.getZoneCode());
                            taskDetail.setPkQty(inventory.getHoldQuantity());
                            taskDetail.setInvCount(inventory.getHoldQuantity().add(inventory.getAvailableQuantity()));
                            taskDetail.setElName(inventory.getMaterialName());
                            taskDetail.setPkList(inventory.getBoxNumber());
                            taskDetail.setWaNo(inventory.getWaNo());
                            taskDetail.setSuNo(inventory.getSuNo());
                            taskDetail.setLotNo(inventory.getLotCode());
                            taskDetail.setVmiCode(inventory.getVmiCode());
                            taskDetail.setSourceId(ordersDetail.getOrderDetailCode());
                            taskDetailList.add(taskDetail);
                        } else {
                            /** 不是暂存区则增加Agv任务 */
                            taskDetail.setId(UuidUtil.genCode());
                            taskDetail.setTaskId(wmsTask.getId());
                            taskDetail.setStatus(1);
                            taskDetail.setIsZanCun(0);
                            taskDetail.setTaskCode(snowflake.nextIdStr());
                            taskDetail.setEl_no(inventory.getMaterialCode());
                            taskDetail.setEl_unit(inventory.getElUnit());
                            taskDetail.setPkQty(inventory.getHoldQuantity());
                            taskDetail.setInvCount(inventory.getHoldQuantity().add(inventory.getAvailableQuantity()));
                            taskDetail.setElName(inventory.getMaterialName());
                            taskDetail.setTrayCode(inventory.getTrayCode());
                            taskDetail.setPkList(inventory.getBoxNumber());
                            taskDetail.setZoneCode(inventory.getZoneCode());
                            taskDetail.setWaNo(inventory.getWaNo());
                            taskDetail.setSuNo(inventory.getSuNo());
                            taskDetail.setLotNo(inventory.getLotCode());
                            taskDetail.setVmiCode(inventory.getVmiCode());
                            taskDetail.setSourceId(ordersDetail.getOrderDetailCode());
                            if (inventory.getIsHold() == 1) {
                                taskDetail.setType("在途物料出货");
                            }
                            taskDetailList.add(taskDetail);
                        }
                    inventory.setIsHold(1);
                }
                ordersDetail.setUpdateTime(new Timestamp(new Date().getTime()));
                orderDetails.add(ordersDetail);
            }

            inventoriesList.addAll(list);
        }
        /** 逻辑处理完成后把修改的数据保存 */
        log.info("出库单为" + allById.getSourceDocument() + "的单据生成出库任务：" + taskDetailList);
        inventoryRepository.saveAll(inventoriesList);
        ordersRepository.save(allById);
        orderDetailRepository.saveAll(orderDetails);
        tasksRepository.saveAll(wmsTasksList);
        taskDetailRepository.saveAll(taskDetailList);
        return new Result(200, "success", map);
    }

    @Override
    public String saveOrders(String param) {
        return null;
    }

    @Override
    public String agvCallback(String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        if (null != jsonObject.getString("status") && jsonObject.getString("status").equals("success")) {
            AgvTaskDetail taskCode = agvTaskDetailRepository.findByTaskCode(jsonObject.get("taskCode") + "");
            taskCode.setStatus(2);
            AgvTasks byId = agvTasksRepository.findById(taskCode.getMainId()).orElse(null);
            List<AgvTaskDetail> byMainId = agvTaskDetailRepository.getAgvTaskDetailByMainId(byId.getId());
            List<Integer> collect = byMainId.stream().map(AgvTaskDetail::getStatus).filter(integer -> integer == 1).collect(Collectors.toList());
            if (collect.size() == 0) {
                byId.setStatus(2);
            } else {
                agvTaskDetailRepository.save(taskCode);
            }
        }
        return null;
    }

    @Override
    public Result returnLocation(String param) {
        String trayCode = receiptService.getTrayCode();
        log.info("出库料箱回库接收到：" + trayCode);
        Inventory inventory = inventoryRepository.findByTrayCodeTop(trayCode);
        Location location = locationRepository.findByTrayCode(trayCode);
        if (null != inventory) {
            TaskDetail taskDetailsByContainerCode = taskDetailRepository.getTaskDetailsByContainerCode(inventory.getBoxNumber());
            taskDetailsByContainerCode.setStatus(2);
            taskDetailRepository.save(taskDetailsByContainerCode);
            if (null != inventory.getAvailableQuantity()) {
                if (inventory.getAvailableQuantity().compareTo(new BigDecimal(0)) <= 0) {
                    inventoryRepository.delete(inventory);
                }
            }
        } else {
            return new Result(102, "该料箱已扫描，请勿重复！", null);
        }
        Tasks wmsTasks = new Tasks();
        wmsTasks.setId(UuidUtil.genCode());
        wmsTasks.setTaskType(8);
        wmsTasks.setTaskCode(UuidUtil.genUuid().toString());
        wmsTasks.setLocationFrom("CY02");
//        wmsTasks.setLocationTo(byTrayCode.get(0).getWarehouseLocation());
        wmsTasks.setTrayCode(trayCode);
        wmsTasks.setStartTime(new Timestamp(new Date().getTime()));
        JSONObject agvTask = new JSONObject();
        agvTask.put("taskType", "putaway");
//        agvTask.put("groupPriority", "0");
        List<JSONObject> tasksList = new ArrayList<>();
        JSONObject tasks = new JSONObject();
        tasks.put("taskCode", wmsTasks.getTaskCode());
        tasks.put("taskPriority", 0);
        JSONObject taskDescribe = new JSONObject();
        String account = "";
//        if (account.equals("admin")) {
//            taskDescribe.put("fromLocationCode", "LT_CONVEYOR_OUTPUT:POINT:26965:11110");
//        } else if (account.equals("song")) {
//            taskDescribe.put("fromLocationCode", "LT_CONVEYOR_OUTPUT:POINT:26965:9160");
//        }
        List<Location> byStatus = new ArrayList<>();
        if (null != location && inventory.getAvailableQuantity().compareTo(new BigDecimal(0)) >= 0) {
            if (trayCode.contains("A")) {
                taskDescribe.put("toLocationCode", inventory.getWarehouseLocation());
            } else if (trayCode.equals("B")) {
                byStatus = locationRepository.getByStatus("0", "%HW%");
                taskDescribe.put("toLocationCode", byStatus.get(0).getLocationCode());
            }
        } else {
            taskDescribe.put("toLocationCode", inventory.getLocationCode());
        }
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("conveyorCodes", trayCode);
//        String s1 = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/expand/api/conveyor/queryConveyor", jsonObject);
//        JSONObject jsonObject2 = JSON.parseObject(s1);
//        String containerCode = jsonObject2.getString("containerCode");
        taskDescribe.put("containerCode", trayCode);
        tasks.put("taskDescribe", taskDescribe);
        tasksList.add(tasks);
        agvTask.put("tasks", tasksList);
        log.info("出库料箱回库发送给agv任务：" + agvTask);
        String s = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/task/create", agvTask);
        JSONObject jsonObjects = new JSONObject();
        if (SecurityUtils.getCurrentUser().getUsername().equals("admin")) {
            jsonObjects.put("slotCode", "LT_CONVEYOR_OUTPUT:POINT:26965:11110");
        } else {
            jsonObjects.put("slotCode", "LT_CONVEYOR_OUTPUT:POINT:26965:9160");
        }
        jsonObjects.put("containerCode", trayCode);
        jsonObjects.put("direction", "100");
        String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObjects);
        JSONObject jsonObject1 = JSON.parseObject(sp);
        JSONObject jsonObject3 = JSON.parseObject(s);
        if (jsonObject3.getInteger("code") == 0 && jsonObject1.getInteger("code") == 0) {
            wmsTasks.setStatus(2);
            tasksRepository.save(wmsTasks);
            if (null != byStatus && byStatus.size() != 0) {
                AgvTasks agvTasks = new AgvTasks();
                agvTasks.setId(UuidUtil.genCode());
                agvTasks.setBillNumber(tasks.getString("taskCode"));
                agvTasks.setTaskType("空料箱回库");
                agvTasksRepository.save(agvTasks);
                byStatus.get(0).setStatus(2);
                byStatus.get(0).setTrayCode(trayCode);
                locationRepository.save(byStatus.get(0));
            } else {
                AgvTasks agvTasks = new AgvTasks();
                agvTasks.setId(UuidUtil.genCode());
                agvTasks.setBillNumber(tasks.getString("taskCode"));
                agvTasks.setTaskType("有料的料箱回库");
                agvTasksRepository.save(agvTasks);
                location.setStatus(2);
                locationRepository.save(location);
            }
            return new Result(200, "success", null);
        }
        return new Result(0, "AGV未响应", null);

    }

    @Override
    public Map<String,Object> queryOrder(OrdersQueryCriteria criteria, Pageable pageable) throws ParseException {
        String elNo = criteria.getMaterialCode();
        Integer orderType = criteria.getOrderType();
        String sourceDocument = criteria.getSourceDocument();
        String startTime = criteria.getCreateTime();
        String endTime = criteria.getUpdateTime();
        if (null != elNo && commonUtil.isStringNotEmpty(elNo)){
            String sql = "SELECT DISTINCT orders.id AS id, orders.source_document AS sourceDocument, orders.order_type AS orderType, orders.order_status AS orderStatus, orders.plan_qty AS planQty,orders.act_qty AS actQty,orders.is_send_Sccs AS isSendSccs ,orders.create_time AS createTime, orders.su_no AS suNo, orders.update_time AS updateTime, orders.custom AS custom FROM orders WHERE id in(SELECT order_detail.main_id FROM order_detail WHERE material_code ='" +elNo + "')" + queryConditionAndElNo(orderType,sourceDocument,startTime,endTime) + "ORDER BY orders.create_time DESC OFFSET(" + pageable.getPageNumber() * pageable.getPageSize() + ")ROWS FETCH NEXT " + pageable.getPageSize() + " ROWS ONLY" ;
            String sql1 = "SELECT DISTINCT orders.id AS id, orders.source_document AS sourceDocument, orders.order_type AS orderType, orders.order_status AS orderStatus, orders.plan_qty AS planQty,orders.act_qty AS actQty,orders.is_send_Sccs AS isSendSccs ,orders.create_time AS createTime, orders.su_no AS suNo, orders.update_time AS updateTime, orders.custom AS custom FROM orders WHERE id in(SELECT order_detail.main_id FROM order_detail WHERE material_code ='" +elNo + "')" + queryConditionAndElNo(orderType,sourceDocument,startTime,endTime) + "ORDER BY orders.create_time DESC" ;
            List<Map<String, Object>> inventoryListCount = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> count = jdbcTemplate.queryForList(sql1);
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("content", inventoryListCount);
            objectMap.put("totalElements", count.size());
            return objectMap;
        }else{
            String sql = "SELECT DISTINCT orders.id AS id, orders.source_document AS sourceDocument, orders.order_type AS orderType, orders.order_status AS orderStatus, orders.plan_qty AS planQty,orders.act_qty AS actQty,orders.is_send_Sccs AS isSendSccs ,orders.create_time AS createTime, orders.su_no AS suNo, orders.update_time AS updateTime, orders.custom AS custom FROM orders  " + queryCondition(orderType,sourceDocument,startTime,endTime) + " ORDER BY orders.create_time DESC OFFSET(" + pageable.getPageNumber() * pageable.getPageSize() + ")ROWS FETCH NEXT " + pageable.getPageSize() + " ROWS ONLY" ;
            String sql1 = "SELECT DISTINCT orders.id AS id, orders.source_document AS sourceDocument, orders.order_type AS orderType, orders.order_status AS orderStatus, orders.plan_qty AS planQty,orders.act_qty AS actQty,orders.is_send_Sccs AS isSendSccs ,orders.create_time AS createTime, orders.su_no AS suNo, orders.update_time AS updateTime, orders.custom AS custom FROM orders  " + queryCondition(orderType,sourceDocument,startTime,endTime) + " ORDER BY orders.create_time DESC " ;
            List<Map<String, Object>> inventoryListCount = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> count = jdbcTemplate.queryForList(sql1);
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("content", inventoryListCount);
            objectMap.put("totalElements", count.size());
            return objectMap;
        }

    }

    @Override
    public List<String> queryOrderByOut(OrdersQueryCriteria criteria) {
        String elNo = criteria.getMaterialCode();
        Integer orderType = criteria.getOrderType();
        String sourceDocument = criteria.getSourceDocument();
        String startTime = criteria.getCreateTime();
        String endTime = criteria.getUpdateTime();
        if (null != elNo && commonUtil.isStringNotEmpty(elNo)){
            List<String> list = new ArrayList<>();
            String sql = "SELECT  orders.id AS id FROM orders WHERE id in(SELECT order_detail.main_id FROM order_detail WHERE material_code ='" +elNo + "')" + queryConditionAndElNo(orderType,sourceDocument,startTime,endTime) + "ORDER BY orders.create_time DESC" ;
            List<Map<String, Object>> inventoryListCount = jdbcTemplate.queryForList(sql);
            for (Map<String, Object> map : inventoryListCount) {
                list.add(map.get("id") + "");
            }
            return list;
        }else{
            List<String> list = new ArrayList<>();
            String sql = "SELECT  orders.id AS id FROM orders  " + queryCondition(orderType,sourceDocument,startTime,endTime) + " ORDER BY orders.create_time DESC ";
            List<Map<String, Object>> inventoryListCount = jdbcTemplate.queryForList(sql);
            for (Map<String, Object> map : inventoryListCount) {
                list.add(map.get("id") + "");
            }
            return list;
        }
    }

    private String queryCondition(Integer orderType,String sourceDocument,String startTime,String endTime){
        String query = "";
        if (null != orderType){
            query = query + " WHERE order_type = " + orderType;
        }
        if (null != sourceDocument && StringUtils.isNotBlank(sourceDocument)){
            if (commonUtil.isStringNotEmpty(query)){
                query = query + "AND source_document LIKE '%" + sourceDocument + "%'";
            }else{
                query = query + "WHERE source_document LIKE '%" + sourceDocument +"%'";
            }
        }
        if (null != startTime && null != endTime){
            if (commonUtil.isStringNotEmpty(query)){
                query = query + "AND create_time BETWEEN '" + startTime + "' AND '" + endTime + "'";
            }else{
                query = query + "WHERE create_time BETWEEN '" + startTime + "' AND '" + endTime + "'";
            }
        }
        return query;
    }
    private String queryConditionAndElNo(Integer orderType,String sourceDocument,String startTime,String endTime){
        String query = "";
        if (null != orderType){
            query = query + " AND order_type = " + orderType;
        }
        if (null != sourceDocument && StringUtils.isNotBlank(sourceDocument)){
            if (commonUtil.isStringNotEmpty(query)){
                query = query + "AND source_document LIKE '%" + sourceDocument + "%'";
            }else{
                query = query + "AND source_document LIKE '%" + sourceDocument +"%'";
            }
        }
        if (null != startTime && null != endTime){
            if (commonUtil.isStringNotEmpty(query)){
                query = query + "AND create_time BETWEEN '" + startTime + "' AND '" + endTime + "'";
            }else{
                query = query + "WHERE create_time BETWEEN '" + startTime + "' AND '" + endTime + "'";
            }
        }
        return query;
    }


    @Override
    public String rePushSccs(String param) {
        List<Orders> ordersList = JSON.parseArray(param, Orders.class);
        for (Orders orders : ordersList) {
            if (orders.getOrderType() == 1) {
                /** 销售随车单 */
                List<JSONObject> jsonObjectList = new ArrayList<>();
                List<Tasks> tasks = tasksRepository.findBySourceCode(orders.getSourceDocument());
                List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orders.getId());
                List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsBySourceIds(orderDetails.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList()));
                for (OrderDetail orderDetail : orderDetails) {
                    List<Tasks> collect = tasks.stream().filter(item -> item.getTaskCode().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    List<TaskDetail> collect2 = taskDetails.stream().filter(item -> item.getSourceId().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    for (TaskDetail taskDetail : collect2) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("pd_list", orders.getSourceDocument());
                        jsonObject1.put("el_no", taskDetail.getEl_no());
                        jsonObject1.put("pk_list", taskDetail.getPkList());
                        jsonObject1.put("lot_no", taskDetail.getLotNo());
                        jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                        jsonObject1.put("pk_qty", taskDetail.getPkQty());
                        jsonObject1.put("el_unit", taskDetail.getEl_unit());
                        jsonObject1.put("rtd_user", "admin");
                        jsonObjectList.add(jsonObject1);
                    }

                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Sjson", JSON.toJSONString(jsonObjectList));
                log.info("重推销售随车单发送给sccs" + jsonObjectList);
                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportPD08", jsonObject.toJSONString());
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                try {
                    JSONObject jsonObject1 = JSON.parseObject(resp);
                    if (jsonObject1.getBoolean("tran_flg")) {
                        orders.setIsSendSccs(1);
                        ordersRepository.save(orders);
                    }else{
                        log.info("重推失败，原因：" + jsonObject1.getString("message"));
                        return "重推失败，原因：" + jsonObject1.getString("message");
                    }
                } catch (Exception e) {
                    log.info("重推销售随车单失败：" + e.getMessage());
                    return "重推失败";
                }
            } else if (orders.getOrderType() == 2) {
                /** 转仓随车单 */
                List<JSONObject> jsonObjectList = new ArrayList<>();
                List<Tasks> tasks = tasksRepository.findBySourceCode(orders.getSourceDocument());
                List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orders.getId());
                List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsBySourceIds(orderDetails.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList()));
                for (OrderDetail orderDetail : orderDetails) {
                    List<Tasks> collect = tasks.stream().filter(item -> item.getTaskCode().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    List<TaskDetail> collect2 = taskDetails.stream().filter(item -> item.getSourceId().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    for (TaskDetail taskDetail : collect2) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("pd_list", orders.getSourceDocument());
                        jsonObject1.put("el_no", taskDetail.getEl_no());
                        jsonObject1.put("pk_list", taskDetail.getPkList());
                        jsonObject1.put("lot_no", taskDetail.getLotNo());
                        jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                        jsonObject1.put("pk_qty", taskDetail.getPkQty());
                        jsonObject1.put("el_unit", taskDetail.getEl_unit());
                        jsonObject1.put("rtd_user", "admin");
                        jsonObjectList.add(jsonObject1);
                    }

                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Sjson", JSON.toJSONString(jsonObjectList));
                log.info("重推转仓随车单:" + JSON.toJSONString(jsonObjectList));
                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportPD03", jsonObject.toJSONString());
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                try {
                    JSONObject jsonObject1 = JSON.parseObject(resp);
                    if (jsonObject1.getBoolean("tran_flg")) {
                        orders.setIsSendSccs(1);
                        ordersRepository.save(orders);
                    }else{
                        log.info("重推失败，原因：" + jsonObject1.getString("message"));
                        return "重推失败，原因：" + jsonObject1.getString("message");
                    }
                } catch (Exception e) {
                    log.info("重推转仓随车单失败：" + e.getMessage());
                    return "重推失败";
                }
            } else if (orders.getOrderType() == 3) {
                /** 销售指令 */
                List<JSONObject> jsonObjectList = new ArrayList<>();
                List<Tasks> tasks = tasksRepository.findBySourceCode(orders.getSourceDocument());
                List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsByTaskIds(tasks.stream().map(Tasks::getId).collect(Collectors.toList()));
                List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orders.getId());
                for (OrderDetail orderDetail : orderDetails) {
                    List<Tasks> collect = tasks.stream().filter(item -> item.getTaskCode().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    for (Tasks tasks1 : collect) {
                        List<TaskDetail> collect1 = taskDetails.stream().filter(item -> item.getTaskId().equals(tasks1.getId())).collect(Collectors.toList());
                        for (TaskDetail taskDetail : collect1) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("pd_list", orders.getSourceDocument());
                            jsonObject1.put("el_no", taskDetail.getEl_no());
                            jsonObject1.put("pk_list", taskDetail.getPkList());
                            jsonObject1.put("lot_no", taskDetail.getLotNo());
                            jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                            jsonObject1.put("pk_qty", taskDetail.getPkQty());
                            jsonObject1.put("el_unit", tasks1.getElUnit());
                            jsonObject1.put("rtd_user", "admin");
                            jsonObjectList.add(jsonObject1);
                        }
                    }
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Sjson", jsonObjectList);
                log.info("重推销售指令:" + jsonObject);
                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportPD07", jsonObjectList);
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                try {
                    JSONObject jsonObject1 = JSON.parseObject(resp);
                    if (jsonObject1.getBoolean("tran_flg")) {
                        orders.setIsSendSccs(1);
                        ordersRepository.save(orders);
                    }else{
                        log.info("重推失败，原因：" + jsonObject1.getString("message"));
                        return "重推失败，原因：" + jsonObject1.getString("message");
                    }
                } catch (Exception e) {
                    log.info("重推销售指令失败：" + e.getMessage());
                    return "重推失败";
                }
            } else if (orders.getOrderType() == 4) {
                /** 成本中心领用 */
                List<JSONObject> jsonObjectList = new ArrayList<>();
                List<Tasks> tasks = tasksRepository.findBySourceCode(orders.getSourceDocument());
                List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsByTaskIds(tasks.stream().map(Tasks::getId).collect(Collectors.toList()));
                List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orders.getId());
                for (OrderDetail orderDetail : orderDetails) {
                    List<Tasks> collect = tasks.stream().filter(item -> item.getTaskCode().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    for (Tasks tasks1 : collect) {
                        List<TaskDetail> collect1 = taskDetails.stream().filter(item -> item.getTaskId().equals(tasks1.getId())).collect(Collectors.toList());
                        for (TaskDetail taskDetail : collect1) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("mr_list", orders.getSourceDocument());
                            jsonObject1.put("el_no", taskDetail.getEl_no());
                            jsonObject1.put("pk_list", taskDetail.getPkList());
                            jsonObject1.put("lot_no", taskDetail.getLotNo());
                            jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                            jsonObject1.put("pk_qty", taskDetail.getPkQty());
                            jsonObject1.put("el_unit", tasks1.getElUnit());
                            jsonObject1.put("rtd_user", "admin");
                            jsonObjectList.add(jsonObject1);
                        }
                    }
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Sjson", JSON.toJSONString(jsonObjectList));
                log.info("重推成本中心领用:" + jsonObject);
                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportMR02", jsonObject);
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                try {
                    JSONObject jsonObject1 = JSON.parseObject(resp);
                    if (jsonObject1.getBoolean("tran_flg")) {
                        orders.setIsSendSccs(1);
                        ordersRepository.save(orders);
                    }else{
                        log.info("重推失败，原因：" + jsonObject1.getString("message"));
                        return "重推失败，原因：" + jsonObject1.getString("message");
                    }
                } catch (Exception e) {
                    log.info("重推成本中心领用发生异常：" + e.getMessage());
                    return "重推失败";
                }
            } else if (orders.getOrderType() == 5) {
                List<JSONObject> jsonObjectList = new ArrayList<>();
                List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orders.getId());
                List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsBySourceIdsOne(orderDetails.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList()));
                for (OrderDetail orderDetail : orderDetails) {
                    List<TaskDetail> collect1 = taskDetails.stream().filter(item -> item.getSourceId().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    for (TaskDetail taskDetail : collect1) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("el_no", taskDetail.getEl_no());
                        jsonObject1.put("mr_list", orders.getSourceDocument());
                        jsonObject1.put("vmi_code", null != taskDetail.getVmiCode() ? taskDetail.getVmiCode() : "");
                        jsonObject1.put("lot_no", taskDetail.getLotNo());
                        jsonObject1.put("pk_qty", taskDetail.getPkQty());
                        jsonObject1.put("pk_list", taskDetail.getPkList());
                        jsonObject1.put("rtd_user", "admin");
                        jsonObjectList.add(jsonObject1);
                    }

                }
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("Sjson", JSON.toJSONString(jsonObjectList));
                log.info("来源单据号为" + orders.getSourceDocument() + "311转仓出库发送给sccs" + jsonObjectList);
                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportMR03", jsonObject1);
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                log.info("来源单据号为" + orders.getSourceDocument() + "311转仓出库sccs回调返回" + resp);
                JSONObject returnJson = JSON.parseObject(resp);
                if (returnJson.getBoolean("tran_flg")) {
                    orders.setIsSendSccs(1);
                    ordersRepository.save(orders);
                } else {
                    log.info("来源单据号为" + orders.getSourceDocument() + "311转仓出库推送sccs失败，返回 ：" + resp);
                    return "重推失败，原因：" + jsonObject1.getString("message");
                }
            }else if(orders.getOrderType() == 6){
                List<JSONObject> jsonObjectList = new ArrayList<>();
                List<Tasks> tasks = tasksRepository.findBySourceCode(orders.getSourceDocument());
                List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsByTaskIds(tasks.stream().map(Tasks::getId).collect(Collectors.toList()));
                List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orders.getId());
                for (OrderDetail orderDetail : orderDetails) {
                    List<Tasks> collect = tasks.stream().filter(item -> item.getTaskCode().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                    for (Tasks tasks1 : collect) {
                        List<TaskDetail> collect1 = taskDetails.stream().filter(item -> item.getTaskId().equals(tasks1.getId())).collect(Collectors.toList());
                        for (TaskDetail taskDetail : collect1) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("el_no", taskDetail.getEl_no());
                            jsonObject1.put("mr_list", orders.getSourceDocument());
                            jsonObject1.put("lot_no", taskDetail.getLotNo());
                            jsonObject1.put("pk_qty", taskDetail.getPkQty());
                            jsonObject1.put("pk_list", taskDetail.getPkList());
                            jsonObject1.put("rtd_user", "admin");
                            jsonObjectList.add(jsonObject1);
                        }
                    }
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Sjson", JSON.toJSONString(jsonObjectList));
                log.info("重推411出库:" + jsonObject);
                String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSImportMR03", jsonObject);
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                try {
                    JSONObject jsonObject1 = JSON.parseObject(resp);
                    if (jsonObject1.getBoolean("tran_flg")) {
                        orders.setIsSendSccs(1);
                        ordersRepository.save(orders);
                    }else{
                        log.info("重推失败，原因：" + jsonObject1.getString("message"));
                        return "重推失败，原因：" + jsonObject1.getString("message");
                    }
                } catch (Exception e) {
                    log.info("重推411出库发生异常：" + e.getMessage());
                    return "重推失败";
                }
            }
        }
        return "重推成功";
    }

    @Override
    public List<TaskDetail> getCountByOrderId(String orderId) {
        Orders orders = ordersRepository.findById(orderId).orElse(null);
        if (null != orders) {
            List<OrderDetail> byMainId = orderDetailRepository.findByMainId(orderId);
            List<String> collect = byMainId.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
            List<TaskDetail> taskDetailsBySourceIds = taskDetailRepository.getTaskDetailsBySourceIds(collect);
            List<TaskDetail> collect1 = taskDetailsBySourceIds.stream().filter(item -> null != item && null != item.getIsZanCun() && item.getIsZanCun() == 1).collect(Collectors.toList());
            return collect1;
        }
        return null;
    }

    /**
     * 料箱回库
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String outBoundByLocationCode(String param) {
        Snowflake snowflake = new Snowflake();

        String toLocationCode = "";
        String snowId = snowflake.nextIdStr();
        String trayCode1 = receiptService.getTrayCode();
        log.info("料箱号为" + trayCode1 + "的料箱准备回库");
        if (null == trayCode1 || trayCode1.equals("")) {
            Inventory inventory = inventoryRepository.findByBoxNumber(param);
            if (null != inventory && inventory.getWarehouseLocation().equals("暂存区")){
                TaskDetail taskDetail = taskDetailRepository.getTaskDetailByPkListAndIsZanCunAndStatus(param);
                if (taskDetail.getStatus() == 2){
                    return "请勿重复扫描";
                }
                taskDetail.setStatus(2);
                taskDetailRepository.save(taskDetail);
                OrderDetail orderDetail = orderDetailRepository.findByOrderDetailCode(taskDetail.getSourceId());
                List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceId(orderDetail.getOrderDetailCode());
                boolean flag = false;
                for (TaskDetail detail : taskDetailList) {
                    if (detail.getStatus() != 2){
                        flag = true;
                    }
                }
                if (!flag){
                    orderDetail.setStatus(2);
                    orderDetail.setActQty(orderDetail.getActQty().add(taskDetail.getPkQty()));
                    orderDetailRepository.save(orderDetail);
                    Orders orders = ordersRepository.findById(orderDetail.getMainId()).orElse(null);
                    List<OrderDetail> orderDetailList = orderDetailRepository.findByMainId(orders.getId());
                    boolean flag1 = false;
                    for (OrderDetail detail : orderDetailList) {
                        if (detail.getStatus() != 2){
                            flag = true;
                        }
                    }
                    if (!flag){
                        orders.setOrderStatus(2);
                        orders.setActQty(orders.getPlanQty());
                        ordersRepository.save(orders);
                        List<Orders> ordersList = new ArrayList<>();
                        ordersList.add(orders);
                        this.rePushSccs(JSON.toJSONString(ordersList));
                    }
                }
                inventory.setHoldQuantity(new BigDecimal(0));
                inventory.setIsHold(0);
                if (inventory.getAvailableQuantity().intValue() == 0){
                    inventoryRepository.deleteById(inventory.getId());
                }else{
                    inventoryRepository.save(inventory);
                }

                return "暂存区出货成功！";
            }
            return "fail";
        }
        if (param.equals("S")) {
            return "当前中文输入法，请切换至英文";
        }
        Inventory inventory = inventoryRepository.findByBoxNumber(param);
        if (null != inventory) {
            TaskDetail taskDetail = taskDetailRepository.getTaskDetailsByContainerCode(inventory.getBoxNumber());
            if (null == taskDetail) {
                return "请勿重复扫描";
            }
            if (taskDetail.getIsZanCun() == 1){
                return "当前扫描的是暂存区物料，但拣选位有货，请先出拣选位的物料";
            }
            if (taskDetail.getStatus() == 2) {
                return "请勿重复扫描";
            }
                taskDetail.setStatus(2);
                taskDetailRepository.save(taskDetail);
            Inventory in = inventoryRepository.findByBoxNumberAndCount(param);
            if (null != in) {
                inventoryRepository.deleteById(inventory.getId());
                Location location = locationRepository.findByTrayCode(trayCode1);
                if (null != location && null != location.getLocationCode()){
                    toLocationCode = location.getLocationCode();
                }else{
                    toLocationCode = inventory.getLocationCode();
                }
                AgvTasks agvTasks = new AgvTasks();
                agvTasks.setId(UuidUtil.genCode());
                agvTasks.setBillNumber(snowId);
                agvTasks.setTaskType("空料箱回库");
                agvTasks.setCreateTime(new Timestamp(new Date().getTime()));
                agvTasksRepository.save(agvTasks);
                JSONObject jsonObjects = new JSONObject();
                jsonObjects.put("taskType", "putaway");
//                jsonObjects.put("groupPriority", 1);
                jsonObjects.put("taskGroupCode", UuidUtil.genCode());
                List<JSONObject> tasks = new ArrayList<>();
                JSONObject jsonObject1 = new JSONObject();
                JSONObject task = new JSONObject();
                task.put("taskCode", snowId);
                Tasks tasks1 = new Tasks();
                tasks1.setId(snowflake.nextIdStr());
                tasks1.setTaskCode(task.getString("taskCode"));
                tasks1.setTaskType(9);
                tasks1.setStatus(1);
                tasks1.setLocationTo(inventory.getWarehouseLocation());
                if (SecurityUtils.getCurrentUsername().equals("admin")){
                    tasks1.setLocationFrom("CY01");
                }else{
                    tasks1.setLocationFrom("CY02");
                }
                tasks1.setTrayCode(trayCode1);
                tasksRepository.save(tasks1);
                task.put("taskPriority", 1);
//            jsonObject1.put("fromLocationCode",location.getLocationCode());
                jsonObject1.put("containerCode", trayCode1);
                jsonObject1.put("storageTag", "");
//            List<String> strings = new ArrayList<>();
//            strings.add("CY01");
//            jsonObject1.put("toStationCode",strings);
                jsonObject1.put("toLocationCode", toLocationCode);
                task.put("taskDescribe", jsonObject1);
                tasks.add(task);
                jsonObjects.put("tasks", tasks);
                log.info("出库空料箱回库发送给AGV" + jsonObjects.toJSONString());
                String url = "http://" + agvIp + ":" + agvPort + "/task/create";
                String s = commonUtil.httpPost(url, JSON.toJSONString(jsonObjects));
                JSONObject jsonObject = JSON.parseObject(s);
                if (jsonObject.getInteger("code") == 0) {
                    JSONObject jsonObject2 = new JSONObject();
                    if (SecurityUtils.getCurrentUsername().equals("admin")) {
                        jsonObject2.put("slotCode", "1-5");
                    } else {
                        jsonObject2.put("slotCode", "2-5");
                    }
                    jsonObject2.put("containerCode", trayCode1);
                    jsonObject2.put("direction", "100");
                    String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObject2.toJSONString());
                    log.info("流动通知返回：" + sp);
                    Location byTrayCode = locationRepository.findLocationByLocationCode(toLocationCode);
                    byTrayCode.setStatus(2);
                    byTrayCode.setTrayCode(trayCode1);
                    locationRepository.save(byTrayCode);
                }
                return "OK";
            } else {
                Location byStatusAndOut = locationRepository.findLocationByLocationCode(inventory.getWarehouseLocation());
                Location location = byStatusAndOut;
                JSONObject jsonObjects = new JSONObject();
                jsonObjects.put("taskType", "putaway");
//                jsonObjects.put("groupPriority", 1);
                jsonObjects.put("taskGroupCode", UuidUtil.genCode());
                List<JSONObject> tasks = new ArrayList<>();
                JSONObject jsonObject1 = new JSONObject();
                JSONObject task = new JSONObject();
                task.put("taskCode", snowId);
                Tasks tasks1 = new Tasks();
                tasks1.setId(snowflake.nextIdStr());
                tasks1.setTaskCode(task.getString("taskCode"));
                tasks1.setLocationTo(inventory.getWarehouseLocation());
                tasks1.setTaskType(9);
                tasks1.setStatus(1);
                tasks1.setTrayCode(trayCode1);
                if (SecurityUtils.getCurrentUsername().equals("admin")){
                    tasks1.setLocationFrom("CY01");
                }else{
                    tasks1.setLocationFrom("CY02");
                }
                tasksRepository.save(tasks1);
                task.put("taskPriority", 1);
//            jsonObject1.put("fromLocationCode",location.getLocationCode());
                String trayCode = receiptService.getTrayCode();
                jsonObject1.put("containerCode", trayCode);
                if (toLocationCode.equals("")) {
                    toLocationCode = inventory.getWarehouseLocation();
                    AgvTasks agvTasks = new AgvTasks();
                    agvTasks.setId(UuidUtil.genCode());
                    agvTasks.setBillNumber(snowId);
                    agvTasks.setTaskType("有料的料箱回库");
                    agvTasks.setCreateTime(new Timestamp(new Date().getTime()));
                    agvTasksRepository.save(agvTasks);
                    jsonObject1.put("toLocationCode", toLocationCode);
                } else {
                    jsonObject1.put("toLocationCode", location.getLocationCode());
                }
                jsonObject1.put("storageTag", "");
//            List<String> strings = new ArrayList<>();
//            strings.add("CY01");
//            jsonObject1.put("toStationCode",strings);
                task.put("taskDescribe", jsonObject1);
                tasks.add(task);
                jsonObjects.put("tasks", tasks);
                log.info("出库有料的料箱回库发送给AGV" + jsonObjects.toJSONString());
                String url = "http://" + agvIp + ":" + agvPort + "/task/create";
                String s = commonUtil.httpPost(url, JSON.toJSONString(jsonObjects));
                JSONObject jsonObject = JSON.parseObject(s);
                if (jsonObject.getInteger("code") == 0) {
                    JSONObject jsonObject2 = new JSONObject();
                    if (SecurityUtils.getCurrentUsername().equals("admin")) {
                        jsonObject2.put("slotCode", "1-5");
                    } else {
                        jsonObject2.put("slotCode", "2-5");
                    }

                    jsonObject2.put("containerCode", trayCode);
                    jsonObject2.put("direction", "100");
                    String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObject2.toJSONString());
                    log.info("流动通知返回：" + sp);
                    location.setTrayCode(trayCode1);
                    location.setStatus(2);
                    inventory.setHoldQuantity(new BigDecimal(0));
                    inventoryRepository.save(inventory);
                    locationRepository.save(location);
                }
                return "OK";
            }

        } else {
            return "未查询到当前物料库存";
        }


    }

    @Override
    public String findCountByTask(String orderId) {
        List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orderId);
        List<String> collect = orderDetails.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
        List<TaskDetail> taskDetailsBySourceIds = taskDetailRepository.getTaskDetailsBySourceIds(collect);
        String result = "";
        for (TaskDetail taskDetail : taskDetailsBySourceIds) {
            OrderDetail orderDetail = orderDetails.stream().filter(item -> item.getOrderDetailCode().equals(taskDetail.getSourceId())).findFirst().orElse(null);
            if (null != orderDetail && orderDetail.getStatus() == 1) {
                result = result + "箱号：" + taskDetail.getPkList() + "  数量：" + taskDetail.getPkQty() + "<br>";
            }
        }
        return result;
    }

    @Override
    public TaskDetail getBoxNumberByTrayCode(String param) {
        JSONObject jsonObjects = JSON.parseObject(param);
        String orderId = jsonObjects.getString("orderId");
        Orders orders = ordersRepository.findById(orderId).orElse(null);
        UserDetails currentUser = SecurityUtils.getCurrentUser();
        JSONObject jsonObject = new JSONObject();
        if (currentUser.getUsername().equals("admin")) {
            List<String> list = new ArrayList<>();
            list.add("1");
            jsonObject.put("conveyorCodes", list);
        } else {
            List<String> list = new ArrayList<>();
            list.add("2");
            jsonObject.put("conveyorCodes", list);
        }
        String s = commonUtil.httpPost("http://" + agvIp + ":" + "9000" + "/equipment/conveyor/queryConveyor", jsonObject.toJSONString());
        log.info("定时查询的输送线箱号返回结果为：" + s);
        JSONObject jsonObject1 = JSON.parseObject(s);
        if (jsonObject1.getInteger("code") != 0) {
            return null;
        }
        JSONObject jsonObject2 = jsonObject1.getJSONObject("data");
        JSONArray conveyors = jsonObject2.getJSONArray("conveyors");
        JSONArray nodeStates = JSON.parseObject(conveyors.get(0).toString()).getJSONArray("nodeStates");
        String containerCode = JSON.parseObject(nodeStates.get(1) + "").getString("containerCode");
        log.info("定时查询的输送线箱号为：" + containerCode);
        if (containerCode.equals("")) {
            return null;
        }
        List<Inventory> byTrayCode = inventoryRepository.findByTrayCode(containerCode);

        if (null != orders && null != byTrayCode && byTrayCode.size() != 0) {
            List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(orderId);
            List<String> collect = orderDetails.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
            List<TaskDetail> taskDetailsBySourceIds = taskDetailRepository.getTaskDetailsBySourceIds(collect);
            TaskDetail taskDetail = taskDetailsBySourceIds.stream().filter(item -> item.getPkList().equals(byTrayCode.get(0).getBoxNumber())).findFirst().orElse(null);
            if (null != taskDetail) {
                return taskDetail;
            }
        }
        return null;
    }


    @Override
    public String outBoundNotRestricted(String param) {
        if (null == param || "".equalsIgnoreCase(param)) {
            return "参数为空，请检查";
        }
        log.info("接收到出库任务" + param);
        List<JSONObject> jsonObject = JSON.parseArray(param, JSONObject.class);
        List<OrderDetail> orderDetails = new ArrayList<>();
        Orders orders = new Orders();
        Snowflake snowflake = new Snowflake();
        String uuid = snowflake.nextIdStr();//头表id
        orders.setId(uuid);
        orders.setIsSendSccs(0);
        orders.setActQty(new BigDecimal(0));
        orders.setOrderCode(UuidUtil.genCode());
        orders.setOrderType(5);
        orders.setOrderStatus(0);
        orders.setCreateTime(new Timestamp(new Date().getTime()));
        BigDecimal planQty = new BigDecimal(0);

        for (JSONObject object : jsonObject) {
            if (null == object.getString("el_no") || object.getString("el_no").equals("")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的物料编号为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的物料编号为空");
            }
            if (null == object.getString("el_name") || object.getString("el_name").equals("")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的物料名称为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的物料名称为空");
            }
            if (null == object.getBigDecimal("mr_qty")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的计划数量为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的计划数量为空");
            }
            List<Inventory> inventories = inventoryRepository.findByMaterialCode(object.getString("el_no"));
            if (null == inventories || inventories.size() == 0) {
                orders.setOrderStatus(4);
            }
            boolean flag = false;
            for (OrderDetail orderDetail : orderDetails) {
                if (orderDetail.getMaterialCode().equals(object.getString("el_no"))) {
                    orderDetail.setPlanQty(orderDetail.getPlanQty().add(object.getBigDecimal("mr_qty")));
                    flag = true;
                }
            }
            if (flag) {
                continue;
            }
            orders.setSourceDocument(object.getString("mr_list"));//随车单号
            OrderDetail order = new OrderDetail();
            order.setId(snowflake.nextIdStr());
            order.setActQty(new BigDecimal(0));
            order.setWarehouseCode(object.getString("mt_area"));
            order.setOrderDetailCode(UuidUtil.genCode());
            order.setMainId(uuid);
            order.setMaterialCode(null != object.getString("el_no") ? object.getString("el_no") : null);//物料编码
            order.setMaterialName(null != object.getString("el_name") ? object.getString("el_name") : null);//物料名称
            order.setPlanQty(null != object.getBigDecimal("mr_qty") ? object.getBigDecimal("mr_qty") : null); //计划数量
            order.setStatus(1);
            planQty = planQty.add(order.getPlanQty());
            order.setWarehouseCode(object.getString("mt_area"));
            order.setSuNo(object.getString("su_no"));
//            order.setLocationCode(null != object.getString("mt_area")?object.getString("mt_area"):null);//发出库位
//            order.setUnitCode(null != object.getString("el_unit")?object.getString("el_unit"):null);//单位
//            order.setCreateBy(null != object.getString("rtd_user")?object.getString("rtd_user"):null);//操作人员
            order.setCreateTime(new Timestamp(new Date().getTime()));
            orderDetails.add(order);
        }
        orders.setPlanQty(planQty);
        ordersRepository.save(orders);
        orderDetailRepository.saveAll(orderDetails);
        return orders.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String quXiao(String param) {
        Orders orders = ordersRepository.findBySourceDocument(param);
        log.info("任务编号为" + orders.getSourceDocument() + "的出库任务需要取消");
        if (orders.getOrderStatus() != 2 || orders.getOrderStatus() == 6) {
            return "1";
        }
        JSONObject jsonObjects = new JSONObject();
        jsonObjects.put("list", param);
        String s = commonUtil.httpPost("http://137.40.151.241:9527/RTDSXWMS/WMSSelectList", jsonObjects);
        log.info("出库任务取消返回数据" + s);
        String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
        JSONObject jsonObjects1 = JSON.parseObject(resp);
        JSONArray jsonObject1 = jsonObjects1.getJSONArray("message");
        List<Receipt> receiptList = new ArrayList<>();
        Snowflake snowflake = new Snowflake();
        for (Object js : jsonObject1) {
            JSONObject jsonObject = JSON.parseObject(js.toString());
            if (jsonObject.getString("el_name").equals("压缩机完成品")) {
                continue;
            }
            int flag = 0;
            /** step 1: 判断当前物料有没有主表 */
            if (receiptList.size() > 0) { // 如果receiptList有值
                for (Receipt receipt : receiptList) {
                    if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                        receipt.setPkQty(receipt.getPkQty().add(jsonObject.getBigDecimal("pd_mrqty")));
                        receipt.setMtQty(receipt.getPkQty().add(jsonObject.getBigDecimal("pd_mrqty")));
                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipt.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pd_mrqty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);
                        flag = 1;   // 找到相同的主表了。
                        break;
                    }
                }
                if (flag == 0) { // 没有Receipt主表
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(null == jsonObject.get("mt_list") ? jsonObject.getString("mt_list") : "");   // 入库单号
//                    receipts.setChNo(jsonObject.get("ch_no")+"");   // 采购订单号
                    receipts.setChSeq(null != jsonObject.get("ch_seq") ? jsonObject.getString("ch_seq") : ""); // 项目号
                    receipts.setSuNo(null != jsonObject.get("su_no") ? jsonObject.getString("su_no") : "");   // 供应商代码
                    receipts.setStatus("0");    // 单据状态
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setMtBwart("出库取消");
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("pd_mrqty"));  // 入库数量
                    receipts.setPkQty(jsonObject.getBigDecimal("pd_mrqty"));  // 入库数量
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea("0015");  // 入库库位
                    receipts.setWaNo(null != jsonObject.get("wa_no") ? String.valueOf(jsonObject.get("wa_no")) : "");  // 工厂
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setVmiCode(null != jsonObject.get("vmi_code") ? String.valueOf(jsonObject.get("vmi_code")) : "");    // 是否VMI
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pd_mrqty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);

                }
            } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                Receipt receipts = new Receipt();
                receipts.setId(IdUtil.simpleUUID());
                receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                receipts.setMtList(null == jsonObject.get("mt_list") ? jsonObject.getString("mt_list") : "");   // 入库单号
//                    receipts.setChNo(jsonObject.get("ch_no")+"");   // 采购订单号
                receipts.setChSeq(null != jsonObject.get("ch_seq") ? jsonObject.getString("ch_seq") : ""); // 项目号
                receipts.setSuNo(null != jsonObject.get("su_no") ? jsonObject.getString("su_no") : "");   // 供应商代码
                receipts.setStatus("0");    // 单据状态
                receipts.setSuName(jsonObject.getString("su_name"));
                receipts.setMtBwart("出库取消");
                receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                receipts.setMtQty(jsonObject.getBigDecimal("pd_mrqty"));  // 入库数量
                receipts.setPkQty(jsonObject.getBigDecimal("pd_mrqty"));  // 入库数量
                receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                receipts.setMtArea("0015");  // 入库库位
                receipts.setWaNo(null != jsonObject.get("wa_no") ? String.valueOf(jsonObject.get("wa_no")) : "");  // 工厂
                receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                receipts.setVmiCode(null != jsonObject.get("vmi_code") ? String.valueOf(jsonObject.get("vmi_code")) : "");    // 是否VMI
                receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                receiptRepository.save(receipts);
                receiptList.add(receipts);
                ReceiptDetail receiptDetail = new ReceiptDetail();
                receiptDetail.setReceiptId(receipts.getId());
                receiptDetail.setId(IdUtil.simpleUUID());
                receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                receiptDetail.setPkQty(jsonObject.getBigDecimal("pd_mrqty"));   // 箱号数量
                receiptDetail.setStatus(1); // 1--未完成入库
                receiptDetailRepository.save(receiptDetail);
            }


        }
        orders.setOrderStatus(6);
        log.info("出库任务取消：" + orders.getSourceDocument() + "生成的入库任务" + receiptList);
        return "success";
    }

    @Override
    public String selectOrderById(String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        List<OrderDetail> orderDetails = orderDetailRepository.findByMainId(jsonObject.getString("orderId"));
        if (null == orderDetails || orderDetails.size() == 0) {
            return "0";
        } else {
            List<String> collect = orderDetails.stream().filter(item -> item.getMaterialName().equals(jsonObject.getString("elName"))).map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
            List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsBySourceIds(collect);
            TaskDetail taskDetail = taskDetails.stream().filter(item -> item.getPkList().length() > 13).findFirst().orElse(null);
            if (null == taskDetail) {
                return "0";
            } else {
                Inventory inventory = inventoryRepository.findByBoxNumber(taskDetail.getPkList());
                JSONObject agvTasks = new JSONObject();
                agvTasks.put("taskType", "tote_outbound");
//                agvTasks.put("groupPriority", 1);
                agvTasks.put("taskGroupCode", UuidUtil.genCode());
                List<JSONObject> tasks = new ArrayList<>();
                JSONObject task = new JSONObject();
                task.put("taskCode", UuidUtil.genCode());
                task.put("taskPriority", 2147);
                JSONObject taskDescribe = new JSONObject();
                taskDescribe.put("containerCode", inventory.getTrayCode());
                List<String> list = new ArrayList<>();
                list.add("CY01");
                taskDescribe.put("toStationCode", list);
                taskDescribe.put("fromLocationCode", inventory.getWarehouseLocation());
                task.put("taskDescribe", taskDescribe);
                tasks.add(task);
                agvTasks.put("tasks", tasks);
                String s = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/task/create", agvTasks);
                JSONObject jsonObject1 = JSON.parseObject(s);
                if (jsonObject1.getInteger("code") == 0) {
                    return "任务已发送，请注意料箱号为" + inventory.getTrayCode() + "的货物";
                }

            }
        }
        return null;
    }

    @Override
    public List<TaskDetail> selectOrderDetailById(String param) {
        String trayCode = receiptService.getTrayCode();
        List<OrderDetail> byMainId = orderDetailRepository.findByMainId(param);
        List<String> collect = byMainId.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
        List<TaskDetail> taskDetailsBySourceIds = taskDetailRepository.getTaskDetailsBySourceIdsOne(collect);
        if (null != trayCode && !"".equals(trayCode)) {
            List<TaskDetail> taskDetail1 = new ArrayList<>();//未完成
            List<TaskDetail> taskDetail2 = new ArrayList<>();//已完成
            List<TaskDetail> taskDetail3 = new ArrayList<>();//已放箱
            List<TaskDetail> taskDetail4 = new ArrayList<>();//已发任务
            List<TaskDetail> taskDetail5 = new ArrayList<>();//暂存区
            List<TaskDetail> taskDetail6 = new ArrayList<>();//当前箱
            List<TaskDetail> returnList = new ArrayList<>();//返回结果
            taskDetailsBySourceIds = taskDetailsBySourceIds.stream().sorted(Comparator.comparing(TaskDetail::getElName)).collect(Collectors.toList());
            for (TaskDetail taskDetail : taskDetailsBySourceIds) {
                if (null != taskDetail.getTrayCode() && taskDetail.getTrayCode().equals(trayCode)) {
                    taskDetail6.add(taskDetail);
                    continue;
                }
                if (taskDetail.getIsZanCun() == 1) {
                    taskDetail5.add(taskDetail);
                    continue;
                }
                if (taskDetail.getStatus() == 1) {
                    taskDetail1.add(taskDetail);
                } else if (taskDetail.getStatus() == 2) {
                    taskDetail2.add(taskDetail);
                } else if (taskDetail.getStatus() == 3) {
                    taskDetail3.add(taskDetail);
                } else if (taskDetail.getStatus() == 4) {
                    taskDetail4.add(taskDetail);
                }
            }
            returnList.addAll(taskDetail6);
            returnList.addAll(taskDetail5);
            returnList.addAll(taskDetail3);
            returnList.addAll(taskDetail4);
            returnList.addAll(taskDetail1);
            returnList.addAll(taskDetail2);
            return returnList;
        } else {
            List<TaskDetail> taskDetail1 = new ArrayList<>();//未完成
            List<TaskDetail> taskDetail2 = new ArrayList<>();//已完成
            List<TaskDetail> taskDetail3 = new ArrayList<>();//已放箱
            List<TaskDetail> taskDetail4 = new ArrayList<>();//已发任务
            List<TaskDetail> taskDetail5 = new ArrayList<>();//暂存区
            List<TaskDetail> returnList = new ArrayList<>();//返回结果
            taskDetailsBySourceIds = taskDetailsBySourceIds.stream().sorted(Comparator.comparing(TaskDetail::getElName)).collect(Collectors.toList());
            for (TaskDetail taskDetail : taskDetailsBySourceIds) {
                if (taskDetail.getIsZanCun() == 1) {
                    taskDetail5.add(taskDetail);
                    continue;
                }
                if (taskDetail.getStatus() == 1) {
                    taskDetail1.add(taskDetail);
                } else if (taskDetail.getStatus() == 2) {
                    taskDetail2.add(taskDetail);
                } else if (taskDetail.getStatus() == 3) {
                    taskDetail3.add(taskDetail);
                } else if (taskDetail.getStatus() == 4) {
                    taskDetail4.add(taskDetail);
                }
            }
            returnList.addAll(taskDetail5);
            returnList.addAll(taskDetail3);
            returnList.addAll(taskDetail4);
            returnList.addAll(taskDetail1);
            returnList.addAll(taskDetail2);
            return returnList;
        }

    }

    /**
     * 不分套出库
     *
     * @param param
     * @return
     */
    @Override
    public String fenTaoOutBound(String param) {
        Orders orders = ordersRepository.findById(param).orElse(null);
        List<TaskDetail> taskDetails = new ArrayList<>();
        List<String> trayCodeList = new ArrayList<>();
        String isZanCun = "";
        if (null != orders) {
            List<OrderDetail> orderDetailList = orderDetailRepository.findByMainId(orders.getId());
            List<String> orderDetailCode = orderDetailList.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
            List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceIds(orderDetailCode);
            JSONObject agvTask = new JSONObject();
            agvTask.put("taskType", "tote_outbound");
            agvTask.put("groupPriority", 3000);
            agvTask.put("taskGroupCode", UuidUtil.genCode());
            Integer i = 0;
            List<JSONObject> tasks = new ArrayList<>();
            List<AgvTasks> agvTasksList = new ArrayList<>();
            for (OrderDetail orderDetail : orderDetailList) {
                List<TaskDetail> taskDetailByOrderDetailCode = taskDetailList.stream().filter(item -> item.getSourceId().equals(orderDetail.getOrderDetailCode())).collect(Collectors.toList());
                taskDetailByOrderDetailCode = taskDetailByOrderDetailCode.stream().sorted(Comparator.comparing(TaskDetail::getElName)).collect(Collectors.toList());
                for (TaskDetail taskDetail : taskDetailByOrderDetailCode) {
                    JSONObject task = new JSONObject();
                    if (taskDetail.getIsZanCun() == 1) {
                        continue;
                    }
                    if (taskDetail.getStatus() != 1) {
                        continue;
                    }
                    task.put("taskCode", taskDetail.getTaskCode());
                    if (taskDetail.getElName().contains("胶盖")) {
                        task.put("taskPriority", 60000 + i);
                    } else if (taskDetail.getElName().contains("胶脚")) {
                        task.put("taskPriority", 50000 + i);
                    } else if (taskDetail.getElName().contains("保护器")) {
                        task.put("taskPriority", 10000 + i);
                    } else {
                        task.put("taskPriority", 1000000 + i);
                    }

                    i = i + 1;
                    taskDetail.setStatus(4);
                    taskDetails.add(taskDetail);
                    JSONObject taskDescribe = new JSONObject();
                    taskDescribe.put("containerCode", taskDetail.getTrayCode());
                    taskDescribe.put("storageTag", "");
                    taskDescribe.put("fromLocationCode", "");
                    List<String> toLocationCode = new ArrayList<>();
                    toLocationCode.add("CY01");
                    taskDetail.setStatus(4);
                    taskDescribe.put("toStationCode", toLocationCode);
                    task.put("taskDescribe", taskDescribe);
                    tasks.add(task);
                    AgvTasks agvTasks = new AgvTasks();
                    agvTasks.setId(UuidUtil.genCode() + i);
                    agvTasks.setStatus(1);
                    agvTasks.setTaskType("carry");
                    agvTasks.setCreateTime(new Timestamp(new Date().getTime()));
                    agvTasks.setTaskGroupCode(agvTask.getString("taskGroupCode"));
                    agvTasks.setBillNumber(taskDetail.getTaskCode());
                    agvTasks.setCreateBy(SecurityUtils.getCurrentUsername());
                    agvTasksList.add(agvTasks);
                }
            }
            agvTask.put("tasks", tasks);
            if (tasks.size() > 0) {
                log.info("不分套出库任务" + orders.getSourceDocument() + "发送给给AGV任务参数：" + agvTask);
                String s = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/task/create", agvTask);
                Result result = JSON.parseObject(s, Result.class);
                log.info("不分套出库收到agv反馈" + result);
                if (result.getCode() != 0) {
                    log.info("不分套出库任务" + orders.getSourceDocument() + "的agv响应异常，原因：" + result);
                    return "订单号为：" + orders.getSourceDocument() + "的订单agv响应异常";
                } else {
                    if (trayCodeList.size() != 0) {
                        List<Location> locationList = locationRepository.findByTrayCodes(trayCodeList);
                        for (int j = 0; j < locationList.size(); j++) {
                            locationList.get(j).setStatus(2);
                        }
                        locationRepository.saveAll(locationList);
                    }
                    taskDetailRepository.saveAll(taskDetails);
                    agvTasksRepository.saveAll(agvTasksList);
                    if (isZanCun.equals("")) {
                        return "success";
                    } else {
                        return "yes";
                    }

                }
            } else {
                return "当前单据下任务均已发送，请勿重复发送";
            }
        }
        return null;
    }

    /**
     * 胶盖胶脚保护器专用分套出库
     *
     * @param param
     * @return
     */
    @Override
    public String fenTaoOther(String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        List<String> trayCodeList = new ArrayList<>();
        List<TaskDetail> taskDetails = new ArrayList<>();
        if (null != jsonObject && null != jsonObject.getString("orderId") && null != jsonObject.getString("elName")) {
            Orders orders = ordersRepository.findById(jsonObject.getString("orderId")).orElse(null);
            if (null != orders) {
                List<OrderDetail> orderDetailList = orderDetailRepository.findByMainId(orders.getId());
                List<String> orderDetailCode = orderDetailList.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
                List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceIds(orderDetailCode);
                JSONObject agvTask = new JSONObject();
                agvTask.put("taskType", "tote_outbound");
                agvTask.put("groupPriority", 2500);
                agvTask.put("taskGroupCode", UuidUtil.genCode());
                Integer i = 0;
                List<JSONObject> tasks = new ArrayList<>();
                List<AgvTasks> agvTasksList = new ArrayList<>();
                for (OrderDetail orderDetail : orderDetailList) {
                    List<TaskDetail> taskDetailByOrderDetailCode = taskDetailList.stream().filter(item -> item.getSourceId().equals(orderDetail.getOrderDetailCode()) && null != item.getElName() && item.getElName().contains(jsonObject.getString("elName")) && item.getStatus() == 1).collect(Collectors.toList());
                    if (null == taskDetailByOrderDetailCode || taskDetailByOrderDetailCode.size() == 0) {
                        continue;
                    }
                    Integer x = 0;
                    taskDetailByOrderDetailCode = taskDetailByOrderDetailCode.stream().sorted(Comparator.comparing(TaskDetail::getElName)).collect(Collectors.toList());
                    for (TaskDetail taskDetail : taskDetailByOrderDetailCode) {
                        if (null != taskDetail.getType() && taskDetail.getType().equals("在途物料出货")){
                            continue;
                        }
                        JSONObject task = new JSONObject();
                        task.put("taskCode", taskDetail.getTaskCode());
                        task.put("taskPriority", 100000 + i);
                        if (x == 6) {
                            break;
                        }
                        i = i + 1;
                        x = x + 1;
                        JSONObject taskDescribe = new JSONObject();
                        taskDetail.setStatus(4);
                        taskDetails.add(taskDetail);
                        taskDescribe.put("containerCode", taskDetail.getTrayCode());
                        taskDescribe.put("storageTag", "");
                        taskDescribe.put("fromLocationCode", "");
                        List<String> toLocationCode = new ArrayList<>();
                        if (taskDetail.getElName().contains("胶脚")) {
                            toLocationCode.add("CY01");
                        } else {
                            toLocationCode.add("CY02");
                        }

                        taskDescribe.put("toStationCode", toLocationCode);
                        task.put("taskDescribe", taskDescribe);
                        tasks.add(task);
                        AgvTasks agvTasks = new AgvTasks();
                        agvTasks.setId(UuidUtil.genCode() + i);
                        agvTasks.setStatus(1);
                        agvTasks.setTaskType("carry");
                        agvTasks.setCreateTime(new Timestamp(new Date().getTime()));
                        agvTasks.setTaskGroupCode(agvTask.getString("taskGroupCode"));
                        agvTasks.setBillNumber(taskDetail.getTaskCode());
                        agvTasks.setCreateBy(SecurityUtils.getCurrentUsername());
                        agvTasksList.add(agvTasks);
                    }
                }
                agvTask.put("tasks", tasks);
                if (tasks.size() > 0) {
                    log.info("任务号为" + orders.getSourceDocument() + "的" + jsonObject.getString("elName") + "发送给AGV任务参数：" + agvTask);
                    String s = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/task/create", agvTask);
                    Result result = JSON.parseObject(s, Result.class);
                    log.info("任务号为" + orders.getSourceDocument() + "的" + jsonObject.getString("elName") + "收到agv反馈" + result);
                    if (result.getCode() != 0) {
                        log.info("任务号为" + orders.getSourceDocument() + "的" + jsonObject.getString("elName") + "agv响应异常，原因：" + result);
                        return "订单号为：" + orders.getSourceDocument() + "的订单agv响应异常";
                    } else {
                        if (trayCodeList.size() != 0) {
                            List<Location> locationList = locationRepository.findByTrayCodes(trayCodeList);
                            for (int j = 0; j < locationList.size(); j++) {
                                locationList.get(j).setStatus(2);
                            }
                            locationRepository.saveAll(locationList);
                        }
                        agvTasksRepository.saveAll(agvTasksList);
                        taskDetailRepository.saveAll(taskDetails);
                        return "success";
                    }
                } else {
                    return "当前单据下的" + jsonObject.getString("elName") + "已经出完，请勿重复点击";
                }
            }
        }
        return null;
    }

    /**
     * 分套出库时先排出的杂料
     *
     * @param param
     * @return
     */
    @Override
    public String fenTaoOtherOne(String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        List<String> trayCodeList = new ArrayList<>();
        List<TaskDetail> taskDetails = new ArrayList<>();
        if (null != jsonObject && null != jsonObject.getString("orderId") && null != jsonObject.getString("elName")) {
            Orders orders = ordersRepository.findById(jsonObject.getString("orderId")).orElse(null);
            if (null != orders) {
                List<OrderDetail> orderDetailList = orderDetailRepository.findByMainId(orders.getId());
                List<String> orderDetailCode = orderDetailList.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
                List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceIds(orderDetailCode);
                JSONObject agvTask = new JSONObject();
                agvTask.put("taskType", "tote_outbound");
                agvTask.put("groupPriority", 5000);
                agvTask.put("taskGroupCode", UuidUtil.genCode());
                Integer i = 0;
                List<JSONObject> tasks = new ArrayList<>();
                List<AgvTasks> agvTasksList = new ArrayList<>();
                for (OrderDetail orderDetail : orderDetailList) {
                    List<TaskDetail> taskDetailByOrderDetailCode = taskDetailList.stream().filter(item -> item.getSourceId().equals(orderDetail.getOrderDetailCode()) && item.getStatus() == 1).collect(Collectors.toList());
                    if (null == taskDetailByOrderDetailCode || taskDetailByOrderDetailCode.size() == 0) {
                        continue;
                    }
                    taskDetailByOrderDetailCode = taskDetailByOrderDetailCode.stream().sorted(Comparator.comparing(TaskDetail::getElName)).collect(Collectors.toList());
                    for (TaskDetail taskDetail : taskDetailByOrderDetailCode) {
                        if (null != taskDetail.getType() && taskDetail.getType().equals("在途物料出货")){
                            continue;
                        }
                        if (taskDetail.getElName().contains("胶盖") || taskDetail.getElName().contains("胶脚") || taskDetail.getElName().contains("保护器")){
                            continue;
                        }
                        if (null != taskDetail.getIsZanCun() && taskDetail.getIsZanCun() == 1){
                            continue;
                        }
                        JSONObject task = new JSONObject();
                        task.put("taskCode", taskDetail.getTaskCode());
                        task.put("taskPriority", 1000000 + i);
                        i = i + 1;
                        JSONObject taskDescribe = new JSONObject();
                        taskDetail.setStatus(4);
                        taskDescribe.put("containerCode", taskDetail.getTrayCode());
                        taskDescribe.put("storageTag", "");
                        taskDescribe.put("fromLocationCode", "");
                        List<String> toLocationCode = new ArrayList<>();
                        toLocationCode.add("CY01");
                        taskDescribe.put("toStationCode", toLocationCode);
                        trayCodeList.add(taskDetail.getTrayCode());
                        task.put("taskDescribe", taskDescribe);
                        tasks.add(task);
                        AgvTasks agvTasks = new AgvTasks();
                        agvTasks.setId(UuidUtil.genCode() + i);
                        agvTasks.setStatus(1);
                        agvTasks.setTaskType("carry");
                        agvTasks.setCreateTime(new Timestamp(new Date().getTime()));
                        agvTasks.setTaskGroupCode(agvTask.getString("taskGroupCode"));
                        agvTasks.setBillNumber(taskDetail.getTaskCode());
                        agvTasks.setCreateBy(SecurityUtils.getCurrentUsername());
                        agvTasksList.add(agvTasks);
                        taskDetails.add(taskDetail);
                    }
                }
                agvTask.put("tasks", tasks);
                if (tasks.size() > 0) {
                    log.info(orders.getSourceDocument() + "分套时先出货的杂物发送给AGV任务参数：" + agvTask);
                    String s = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/task/create", agvTask);
                    Result result = JSON.parseObject(s, Result.class);
                    log.info("分套时先出货的杂物收到agv反馈" + result);
                    if (result.getCode() != 0) {
                        log.info(orders.getSourceDocument() + "分套时先出货的杂物agv响应异常，原因：" + result);
                        return "订单号为：" + orders.getSourceDocument() + "的订单agv响应异常";
                    } else {
                        if (trayCodeList.size() != 0) {
                            List<Location> locationList = locationRepository.findByTrayCodes(trayCodeList);
                            for (int j = 0; j < locationList.size(); j++) {
                                locationList.get(j).setStatus(2);
                            }
                            locationRepository.saveAll(locationList);
                        }
                        taskDetailRepository.saveAll(taskDetails);
                        agvTasksRepository.saveAll(agvTasksList);
                        return "success";
                    }
                }
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String wanCheng(String param) {
        Orders orders = ordersRepository.findById(param).orElse(null);
        if (null != orders) {
            List<OrderDetail> orderDetailList = orderDetailRepository.findByMainId(orders.getId());
            List<String> orderDetailCodeList = orderDetailList.stream().map(OrderDetail::getOrderDetailCode).collect(Collectors.toList());
            List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceIds(orderDetailCodeList);
            List<String> pkList = taskDetailList.stream().map(TaskDetail::getPkList).collect(Collectors.toList());
            List<Inventory> inventoryList = inventoryRepository.findByBoxNumbers(pkList);
            for (Inventory inventory : inventoryList) {
                if (inventory.getAvailableQuantity().compareTo(new BigDecimal(0)) <= 0) {
                    inventoryRepository.delete(inventory);
                } else {
                    inventory.setHoldQuantity(new BigDecimal(0));
                    inventory.setIsHold(0);
                    inventoryRepository.save(inventory);
                    if (!inventory.getWarehouseLocation().equals("暂存区")) {
                        Location location = locationRepository.findByTrayCode(inventory.getTrayCode());
                        location.setStatus(1);
                        locationRepository.save(location);
                    }
                }
            }
            taskDetailList.stream().forEach(item -> {
                item.setStatus(2);
            });
            orderDetailList.stream().forEach(item -> {
                item.setStatus(2);
                item.setActQty(item.getPlanQty());
            });
            orders.setOrderStatus(2);
            orders.setActQty(orders.getPlanQty());
            taskDetailRepository.saveAll(taskDetailList);
            ordersRepository.save(orders);
            orderDetailRepository.saveAll(orderDetailList);
            return "success";
        }
        return "fail";
    }

    @Override
    public Result getTaskDetailCountByOrderId(String param) {
        Orders orders = ordersRepository.findById(param).orElse(null);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        if (null != orders) {
            List<OrderDetail> orderDetailList = orderDetailRepository.findByMainId(orders.getId());
            for (OrderDetail orderDetail : orderDetailList) {
                if (orderDetail.getMaterialName().contains("胶盖")) {
                    List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceId(orderDetail.getOrderDetailCode());
                    if (null != taskDetailList && taskDetailList.size() != 0) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(orderDetail.getMaterialName(), taskDetailList.size());
                        jsonObjectList.add(jsonObject);
                    }
                } else if (orderDetail.getMaterialName().contains("胶脚")) {
                    List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceId(orderDetail.getOrderDetailCode());
                    if (null != taskDetailList && taskDetailList.size() != 0) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(orderDetail.getMaterialName(), taskDetailList.size());
                        jsonObjectList.add(jsonObject);
                    }
                } else if (orderDetail.getMaterialName().contains("过载保护器")) {
                    List<TaskDetail> taskDetailList = taskDetailRepository.getTaskDetailsBySourceId(orderDetail.getOrderDetailCode());
                    if (null != taskDetailList && taskDetailList.size() != 0) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(orderDetail.getMaterialName(), taskDetailList.size());
                        jsonObjectList.add(jsonObject);
                    }
                } else {
                    break;
                }
            }
            if (null != jsonObjectList && jsonObjectList.size() != 0) {
                return new Result(200, "success", jsonObjectList);
            }
        }
        return new Result(0, "fail", null);
    }

    @Override
    public String outBoundReturn(String param) {
        param = StrUtil.strip(param, "\"").replaceAll("\\\\", "");
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mt_list"); // 出库取消 入库单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "fail"; // 重复的入库单
            }

            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("mt_list")));   // 入库单号
                        receipts.setChNo(jsonObject.get("ch_no").toString());   // 采购订单号
                        receipts.setChSeq(jsonObject.get("ch_seq").toString()); // 项目号
                        receipts.setSuNo(jsonObject.get("su_no").toString());   // 供应商代码
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName("su_name");
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mt_qty"));  // 入库数量
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                        receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                        receipts.setVmiCode(String.valueOf(jsonObject.get("vmi_code")));    // 是否VMI
                        receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mt_list")));   // 入库单号
                    receipts.setChNo(jsonObject.get("ch_no").toString());   // 采购订单号
                    receipts.setChSeq(jsonObject.get("ch_seq").toString()); // 项目号
                    receipts.setSuNo(jsonObject.get("su_no").toString());   // 供应商代码
                    receipts.setStatus("0");    // 单据状态'
                    receipts.setSuName("su_name");
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mt_qty"));  // 入库数量
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                    receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setVmiCode(String.valueOf(jsonObject.get("vmi_code")));    // 是否VMI
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String outBoundByInventory(String param) {
        List<Inventory> inventoryList = JSON.parseArray(param, Inventory.class);
        List<String> collect = inventoryList.stream().map(Inventory::getBoxNumber).collect(Collectors.toList());
        List<TaskDetail> taskDetails = taskDetailRepository.getTaskDetailsByBoxNumberAndType(collect);
        inventoryList = inventoryList.stream().sorted(Comparator.comparing(Inventory::getMaterialCode)).collect(Collectors.toList());
        JSONObject agvTask = new JSONObject();
        agvTask.put("taskType", "tote_outbound");
//        agvTask.put("groupPriority", 1);
        agvTask.put("taskGroupCode", UuidUtil.genCode());
        List<JSONObject> tasks = new ArrayList<>();
        List<AgvTasks> agvTasksList = new ArrayList<>();
        List<TaskDetail> taskDetailList = new ArrayList<>();
        Integer i = 0;
        Tasks tasks1 = new Tasks();
        tasks1.setId(UuidUtil.genCode());
        tasks1.setStatus(0);
        tasks1.setTaskType(7);//暂定7为冻结出库
        tasks1.setCreateTime(new Timestamp(new Date().getTime()));
        for (Inventory inventory : inventoryList) {
            //生成AGV任务，和wms系统的任务
            List<TaskDetail> collect1 = taskDetails.stream().filter(item -> item.getPkList().equals(inventory.getBoxNumber())).collect(Collectors.toList());
            if (null != collect1 && collect1.size() > 0) {
                continue;
            }
            JSONObject task = new JSONObject();
            task.put("taskCode", UuidUtil.genCode() + i);
            task.put("taskPriority", i);
            JSONObject taskDescribe = new JSONObject();
            taskDescribe.put("containerCode", inventory.getTrayCode());
            taskDescribe.put("storageTag", "");
            taskDescribe.put("fromLocationCode", "");
            List<String> toLocationCode = new ArrayList<>();
            toLocationCode.add("CY01");
            taskDescribe.put("toStationCode", toLocationCode);
            task.put("taskDescribe", taskDescribe);
            tasks.add(task);
            TaskDetail taskDetail = new TaskDetail();
            taskDetail.setId(UuidUtil.genCode() + i);
            taskDetail.setBoxNumber(inventory.getBoxNumber());
            taskDetail.setTaskCode(task.getString("taskCode"));
            taskDetail.setElName(inventory.getMaterialName());
            taskDetail.setEl_no(inventory.getMaterialCode());
            taskDetail.setTaskId(tasks1.getId());
            taskDetail.setPkList(inventory.getBoxNumber());
            taskDetail.setStatus(1);
            taskDetail.setTrayCode(inventory.getTrayCode());
            taskDetail.setCreateTime(new Timestamp(new Date().getTime()));
            taskDetail.setCreateBy(SecurityUtils.getCurrentUsername());
            taskDetail.setType("冻结/解冻出库");
            AgvTasks agvTasks = new AgvTasks();
            agvTasks.setId(UuidUtil.genCode() + i);
            agvTasks.setStatus(1);
            agvTasks.setTaskType("冻结出库");
            agvTasks.setCreateTime(new Timestamp(new Date().getTime()));
            agvTasks.setTaskGroupCode(agvTask.getString("taskGroupCode"));
            agvTasks.setBillNumber(task.getString("taskCode"));
            agvTasks.setCreateBy(SecurityUtils.getCurrentUsername());
            inventory.setIsHold(2);
            agvTasksList.add(agvTasks);
            taskDetailList.add(taskDetail);
        }
        agvTask.put("tasks", tasks);
        if (tasks.size() > 0) {
            String s = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/task/create", agvTask);
            Result result = JSON.parseObject(s, Result.class);
            agvTasksRepository.saveAll(agvTasksList);
            inventoryRepository.saveAll(inventoryList);
            taskDetailRepository.saveAll(taskDetailList);
            return "success";
        }
        return "fail";
    }

    // 411出库
    @Override
    public String outBoundVmiToFree(String param) {
        if (null == param || "".equalsIgnoreCase(param)) {
            return "参数为空，请检查";
        }
        log.info("接收到出库任务" + param);
        List<JSONObject> jsonObject = JSON.parseArray(param, JSONObject.class);
        List<OrderDetail> orderDetails = new ArrayList<>();
        Orders orders = new Orders();
        Snowflake snowflake = new Snowflake();
        String uuid = snowflake.nextIdStr();//头表id
        orders.setId(uuid);
        orders.setIsSendSccs(0);
        orders.setActQty(new BigDecimal(0));
        orders.setOrderCode(UuidUtil.genCode());
        orders.setOrderType(6); //411出库
        orders.setOrderStatus(0);
        orders.setCreateTime(new Timestamp(new Date().getTime()));
        BigDecimal planQty = new BigDecimal(0);
        for (JSONObject object : jsonObject) {
            if (null == object.getString("el_no") || object.getString("el_no").equals("")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的物料编号为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的物料编号为空");
            }
            if (null == object.getString("el_name") || object.getString("el_name").equals("")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的物料名称为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的物料名称为空");
            }
            if (null == object.getBigDecimal("mr_qty")) {
                log.info("出库单号为：" + object.getString("mr_list") + "的计划数量为空");
                throw new RuntimeException("出库单号为：" + object.getString("mr_list") + "的计划数量为空");
            }
            List<Inventory> inventories = inventoryRepository.findByMaterialCode(object.getString("el_no"));
            if (null == inventories || inventories.size() == 0) {
                orders.setOrderStatus(4);
            }
            boolean flag = false;
            for (OrderDetail orderDetail : orderDetails) {
                if (orderDetail.getMaterialCode().equals(object.getString("el_no")) && orderDetail.getSuNo().equals(object.getString("su_no"))) {
                    orderDetail.setPlanQty(orderDetail.getPlanQty().add(object.getBigDecimal("mr_qty")));
                    flag = true;
                }
            }
            if (flag) {
                continue;
            }
            orders.setSourceDocument(object.getString("mr_list"));//随车单号
            OrderDetail order = new OrderDetail();
            order.setId(snowflake.nextIdStr());
            order.setActQty(new BigDecimal(0));
            order.setWarehouseCode(object.getString("mt_area"));
            order.setOrderDetailCode(UuidUtil.genCode());
            order.setMainId(uuid);
            order.setMaterialCode(null != object.getString("el_no") ? object.getString("el_no") : null);//物料编码
            order.setMaterialName(null != object.getString("el_name") ? object.getString("el_name") : null);//物料名称
            order.setPlanQty(null != object.getBigDecimal("mr_qty") ? object.getBigDecimal("mr_qty") : null); //计划数量
            order.setStatus(1);
            planQty = planQty.add(order.getPlanQty());
            order.setWarehouseCode(object.getString("mt_area"));
            order.setSuNo(object.getString("su_no"));
//            order.setLocationCode(null != object.getString("mt_area")?object.getString("mt_area"):null);//发出库位
//            order.setUnitCode(null != object.getString("el_unit")?object.getString("el_unit"):null);//单位
//            order.setCreateBy(null != object.getString("rtd_user")?object.getString("rtd_user"):null);//操作人员
            order.setCreateTime(new Timestamp(new Date().getTime()));
            orderDetails.add(order);
        }
        orders.setPlanQty(planQty);
        ordersRepository.save(orders);
        orderDetailRepository.saveAll(orderDetails);
        return orders.getId();
    }

    @Override
    public int receiveBillNumberFromPDA(String param) {
        /** 推送前端出库订单号 */
        JSONObject jsonObject = JSON.parseObject(param);
        String billNumber = jsonObject.getString("billNumber");
        SocketMsg socketMsg = new SocketMsg(billNumber, MsgType.INFO);
        try {
            WebSocketServer.sendInfo(socketMsg, "777");
        } catch (IOException e) {
            return 0;
        }
        return 1;
    }

    @Override
    public int receiveHuiKuBoxNumberFromPDA(String param) {
        /** 推送前端出库订单号 */
        JSONObject jsonObject = JSON.parseObject(param);
        String boxNumber = jsonObject.getString("boxNumber");
        SocketMsg socketMsg = new SocketMsg(boxNumber, MsgType.HUIKU);
        try {
            WebSocketServer.sendInfo(socketMsg, "777");
        } catch (IOException e) {
            return 0;
        }
        return 1;
    }

}